gpt4 book ai didi

c# - 返回时导致 SEGFAULT 的非托管函数指针

转载 作者:行者123 更新时间:2023-11-30 18:11:38 25 4
gpt4 key购买 nike

我在C中有以下方法

void SSL_CTX_set_cookie_verify_cb(SSL_CTX *ctx,
int (*cb) (SSL *ssl,
const unsigned char *cookie,
unsigned int cookie_len))
{
ctx->app_verify_cookie_cb = cb;
}

我希望在 C# 中调用它。我正在尝试这样:

[DllImport(SSLDLLNAME, CallingConvention = CallingConvention.Cdecl)]
public static extern void SSL_CTX_set_cookie_verify_cb(IntPtr ctx, VerifyCookieDelegate callback);

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate int VerifyCookieDelegate(IntPtr ssl, [MarshalAs(UnmanagedType.LPStr)] string cookie, int cookie_len);

不幸的是,当回调运行时,返回后,进程死于 SIGSEGV(segfault)

    public int VerifyCookieThunk(IntPtr sslPtr, IntPtr cookie, int cookieLength)
{
if (!TryGetInstance(sslPtr, out Ssl ssl))
return Native.FAIL;

var c = new byte[cookieLength];

Marshal.Copy(cookie, c, 0, cookieLength);

if (_verifyCookieCallback(ssl, c))
return 1;

return 0;
}

我觉得奇怪的是当回调返回时发生段错误。所以我想也许我还需要保留对返回值的引用。所以我做了一个类变量(该类不是GCd):

private int verifyCookieResult;

现在在回调中我设置并返回 verifyCookieResult。仍然是段错误。

您可能认为 native 代码中存在错误,但事实并非如此。这个完全相同的函数在不同的上下文中起作用。

是不是我设置回调函数的代码写的有问题?

最佳答案

假设您在 Windows 下运行。

您可能与调用约定不匹配。正如我从您的示例中看到的那样,它设置为 CallingConvention.Cdecl

来自 Wikipedia :

Calling conventions describe the interface of called code:

  • The order in which atomic (scalar) parameters, or individual parts of a complex parameter, are allocated
  • How parameters are passed (pushed on the stack, placed in registers, or a mix of both)
  • Which registers the called function must preserve for the caller (also known as: callee-saved registers or non-volatile registers)
  • How the task of preparing the stack for, and restoring after, a function call is divided between the caller and the callee

来自 MSDN :

The __stdcall calling convention is used to call Win32 API functions.

尝试将您的代码更改为标准调用。

CallingConvention.StdCall

关于c# - 返回时导致 SEGFAULT 的非托管函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57275227/

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