将字符串作为参数从c#传递给c++中的回调函数
Pass a string as argument from C# to callback function in C++
我正在编写一个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
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- 函数调用中参数的顺序重要吗
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用不带参数的函数访问结构元素
- 代码在main()中运行,但在函数中出现错误
- 内置函数可查看CPP中的成员变量
- 如何获取std::result_of函数的返回类型
- 如何在c++中为模板函数实例创建快捷方式
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗