我有一个具有以下签名的 C 函数:
int __declspec(dllexport) __cdecl test(void* p);
函数实现如下:
int i = 9;
int test(void* p)
{
p = &i;
return 0;
}
在 C# 应用程序中,我想通过指向 C# 应用程序的指针返回引用的值,因此我执行了以下操作:
[DllImport(@"lib\test.dll", CallingConvention=CallingConvention.Cdecl)]
public static extern int test(out IntPtr p);
IntPtr p = IntPtr.Zero;
test(out p);
但是,p 没有任何返回值。
请帮忙!!
最佳答案
如果你想改变调用者的指针参数的值,你需要传递一个指向指针的指针:
int test(void** p)
{
*p = &i;
return 0;
}
从 C# 中调用类似的东西
[DllImport(@"lib\test.dll", CallingConvention=CallingConvention.Cdecl)]
public static extern unsafe int test(IntPtr* p);
public unsafe void DotNetFunc()
{
IntPtr p;
test(&p);
如果您不喜欢使用 unsafe
,您可以将 C 函数改为返回一个指针,必要时返回 NULL
以指示错误。
int* test()
{
return &i;
}
[DllImport(@"lib\test.dll", CallingConvention=CallingConvention.Cdecl)]
public static extern IntPtr test();
IntPtr p = test();
if (p == IntPtr.Zero)
// error
关于c# - P/Invoke 返回 void*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20906165/