gpt4 book ai didi

c# - 为什么将字符串从 C# 传递到 C++ dll 会得到 NULL?

转载 作者:太空宇宙 更新时间:2023-11-04 12:46:17 25 4
gpt4 key购买 nike

我正在尝试将 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 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);

关于c# - 为什么将字符串从 C# 传递到 C++ dll 会得到 NULL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51376797/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com