我正在尝试将C#可执行文件连接到C ++ dll。dll的方法之一接收const char *和int *(第一个方法指定输入值,第二个方法指定返回值的地址):
extern "C" __declspec(dllexport)
int setVal(long handle, const char* ptrVal, int* ptrRet);
此函数要做的第一件事是检查ptrVal是否为null,如果是,则返回-1。
另一方面,C#代码按如下方式调用dll:
[DllImport(dllName,
EntryPoint = "setVal",
ExactSpelling = true,
CallingConvention = CallingConvention.Cdecl,
CharSet = CharSet.Ansi)]
public static extern int setVal(long handle,
[MarshalAs(UnmanagedType.LPStr)] string str,
ref int ptrRes);
在主要功能中,我有
long handle = 0;
int result = 0;
int res = 0;
string str = "Hello World!";
result = setVal(handle, str, ref res);
调用此函数时,我总是在C端收到一个空指针,这使结果等于-1。声明包装函数时,我尝试了不同的方法,但没有成功:
public static extern int setVal(long handle,
[MarshalAs(UnmanagedType.LPStr)] [In] string str,
[Out] int ptrRes);
public static unsafe extern int setVal(long handle,
[MarshalAs(UnmanagedType.LPStr)] string str,
ref int ptrRes);
public static extern int setVal(long handle,
StringBuilder sb,
ref int ptrRes); // also the unsafe version
public static extern int setVal(long handle,
byte[] value,
ref int ptrRes); // also the unsafe version
我正在使用Visual Studio 2017和.NET Framework 4.6.1。
为什么我总是收到NULL作为dll函数的第二个参数(const char *)?
我做了一点谷歌,所以这将是未经测试的代码,但我可以看到这是您没有尝试过的东西
像这样声明外部
[DllImport(dllName, EntryPoint = "setVal", ExactSpelling = true, CallingConvention, CallingConvention.Cdecl,CharSet = CharSet.Ansi)]
public static extern int setVal(int handle, StringBuilder sb, ref int ptrRes);
像这样使用
int handle = 0;
int result = 0;
int res = 0;
StringBuilder sb = new StringBuilder("Hello World");
result = setVal(handle, sb, ref res);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句