[英]P/Invoke Return void*
I have a C function with the following signature: 我有一个带有以下签名的C函数:
int __declspec(dllexport) __cdecl test(void* p);
The function implementation is as following: 函数实现如下:
int i = 9;
int test(void* p)
{
p = &i;
return 0;
}
From a C# application, i want to return the value of the reference through the pointer to the C# application, so i did the following: 从C#应用程序,我想通过指向C#应用程序的指针返回引用的值,所以我做了以下工作:
[DllImport(@"lib\test.dll", CallingConvention=CallingConvention.Cdecl)]
public static extern int test(out IntPtr p);
IntPtr p = IntPtr.Zero;
test(out p);
However, p does not have any value back. 但是,p没有任何价值。
Any help please!! 任何帮助,请!
If you want to change the value of the caller's pointer argument, you need to pass a pointer to a pointer: 如果要更改调用者的指针参数的值,则需要将指针传递给指针:
int test(void** p)
{
*p = &i;
return 0;
}
calling from C# something like 从C#调用类似
[DllImport(@"lib\test.dll", CallingConvention=CallingConvention.Cdecl)]
public static extern unsafe int test(IntPtr* p);
public unsafe void DotNetFunc()
{
IntPtr p;
test(&p);
If you don't like the use of unsafe
, you could change your C function to return a pointer instead, returning NULL
to indicate an error if necessary. 如果您不喜欢使用
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
You don't need unsafe code. 您不需要不安全的代码。 But you do need to fix the C code.
但是您确实需要修复C代码。 Like so:
像这样:
void test(int** p)
{
*p = &i;
}
And the C# code is: C#代码是:
[DllImport("...", , CallingConvention=CallingConvention.Cdecl)]
static extern void test(out IntPtr p);
Call it like this: 这样称呼它:
IntPtr p;
test(out p);
And read the value like this: 并读取这样的值:
int i = Marshal.ReadInt32(p);
Or return the pointer as the function return value: 或返回指针作为函数的返回值:
int* test(void)
{
return &i;
}
And in C#: 在C#中:
[DllImport("...", , CallingConvention=CallingConvention.Cdecl)]
static extern IntPtr test();
And I'm sure you can do the rest. 而且我相信您可以做剩下的事情。
Try using pointer of pointer 尝试使用指针的指针
int test(void** p)
{
*p = &i;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.