【发布时间】:2018-07-17 16:51:35
【问题描述】:
我正在尝试将 C# 可执行文件连接到 C++ dll。 dll的一个方法接收一个const char*和一个int*(第一个指定输入值,第二个指定返回值的地址):
extern "C" __declspec(dllexport)
int setVal(long handle, const char* ptrVal, int* ptrRet);
这个函数做的第一件事是检查ptrVal是否为空,如果是则返回-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 框架 4.6.1。
为什么我总是收到 NULL 作为 dll 函数的第二个参数 (const char*)?
【问题讨论】:
-
查看第一个参数的相关信息:docs.microsoft.com/en-gb/cpp/dotnet/… - 将句柄设置为 0,因为 C# long 有效地将 C++ long=0 和字符串的地址传递给 0 (=null)。
标签: c# c++ visual-studio-2017