2011-12-18 166 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

相關問題