2011-12-18 165 views
3

我正在编写一个C#dll包装程序来包装第三方C#dll。 我还需要将此作为Java方法公开,我使用的是一个中间C++层,它封装了我的C#dll并提供了一个JNI机制来公开使用java的相同方法。将C#中的参数作为参数传递给C++中的回调函数

但是,我在将字符串作为参数传递给回调函数时遇到问题,因为它在C++中调用该函数。这是代码。

#include "stdafx.h" 
#include "JavaInclude.h" 
#include <iostream> 
#using "Class1.netmodule" 
#using <mscorlib.dll> 

using namespace std; 
using namespace System; 

int CSomeClass::MemberFunction(void* someParam) 
{ 
    cout<<"Yaay! Callback"<<endl; 
    return 0; 
} 

static int __clrcall SomeFunction(void* someObject, void* someParam, String^ strArg) 
{ 
    CSomeClass* o = (CSomeClass*)someObject; 
    Console::WriteLine(strArg); 
    return o->MemberFunction(someParam); 
} 

JNIEXPORT void JNICALL Java_de_tum_kinect_KinectSpeechInit_initConfig 
    (JNIEnv *env, jobject obj) 
{ 
    array<String^>^ strarray = gcnew array<String^>(5); 
    for(int i=0; i<5; i++) 
      strarray[i] = String::Concat("Number ",i.ToString()); 

    CSomeClass o; 
    void* p = 0; 
    CSharp::Function(System::IntPtr(SomeFunction), System::IntPtr(&o), System::IntPtr(p), strarray); 
} 

这里是我的C#类

using System; 
using System.Runtime.InteropServices; 

public class CSharp 
{ 
    delegate int CFuncDelegate(IntPtr Obj, IntPtr Arg, string strArg); 

    public static void Function(IntPtr CFunc, IntPtr Obj, IntPtr Arg, String[] pUnmanagedStringArray) 
    { 
     CFuncDelegate func = (CFuncDelegate)Marshal.GetDelegateForFunctionPointer(CFunc, typeof(CFuncDelegate)); 

     for (int i = 0; i < pUnmanagedStringArray.Length; i++) 
     { 
      Console.WriteLine(pUnmanagedStringArray[i]); 
     } 
     string strArg = "Test String"; 
     int rc = func(Obj, Arg, strArg); 
    } 
} 

当我在我的C做了Console::WriteLine(strArg); ++ DLL,它只是输出一个空字符串! 如果有人能帮助我,我会非常感激,因为我对这一切都很新颖。

感谢, 迪帕克

回答

3

最有可能的问题是,C++预计在那里为C#创建统一码的人ANSI字符串。

所以,如果你有这个

delegate int CFuncDelegate(IntPtr Obj, IntPtr Arg, [MarshalAs (UnmanagedType.LPSTR)] string strArg); 

替代你可以看看这里的更多信息:http://msdn.microsoft.com/en-us/library/s9ts558h

+0

嘛。这工作!感谢Adam! – deepak 2011-12-18 23:03:46

相关问题