将字符串作为参数从c#传递给c++中的回调函数

Pass a string as argument from C# to callback function in C++

本文关键字:c++ 函数 回调 字符串 参数      更新时间:2023-10-16

我正在编写一个c# dll包装器来包装第三方c# dll。我还需要将其公开为Java方法,为此我使用了一个中间的c++层,该层包装了我的c# dll,并提供了一个JNI机制来使用Java公开相同的方法。

然而,我有一个问题在传递字符串作为参数回调函数时,它在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++ dll中执行Console::WriteLine(strArg);时,它只是打印一个空白字符串!如果有人能帮助我,我将非常感激,因为我对这一切都很陌生。

谢谢,迪帕克

最可能的问题是c++期望ANSI字符串,而c#创建unicode字符串。

所以如果你用这个

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

您可以在这里查看更多信息:http://msdn.microsoft.com/en-us/library/s9ts558h