[英]P/Invoke Return void*
我有一个带有以下签名的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代码。 像这样:
void test(int** p)
{
*p = &i;
}
C#代码是:
[DllImport("...", , CallingConvention=CallingConvention.Cdecl)]
static extern void test(out IntPtr p);
这样称呼它:
IntPtr p;
test(out p);
并读取这样的值:
int i = Marshal.ReadInt32(p);
或返回指针作为函数的返回值:
int* test(void)
{
return &i;
}
在C#中:
[DllImport("...", , CallingConvention=CallingConvention.Cdecl)]
static extern IntPtr test();
而且我相信您可以做剩下的事情。
尝试使用指针的指针
int test(void** p)
{
*p = &i;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.