c# - P/Invoke 返回 void*

标签 c# c pinvoke

我有一个具有以下签名的 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/

相关文章:

c# - linq to实体更改代码中的数据库连接字符串

c# - 使用 c-sharp 进行 FloodFill

.net - 为什么 .NET 程序可以在损坏的堆栈中存活? (使用错误的调用约定时)

c# - 将本地 dll 放在 ASP.NET 项目中的什么位置?

c# - C# 如何在没有中间 C++ 层的情况下直接调用 ml64 dll?

方法中的 C# 线程

c# - WPF 从具有双向绑定(bind)的 ViewModel 中选择 DataGrid 中的多个项目

c - pipe2(...) vs pipe() + fcntl(...),为什么不同?

C共享内存双 vector

谁能看出为什么这个程序会产生段错误