在通过 P/Invoke 获取的 C++ 结构上设置 C# 回调

Set C# callback on a C++ struct obtained via P/Invoke

本文关键字:结构上 C++ 设置 回调 获取 Invoke      更新时间:2023-10-16

我正在尝试使用我得到的外部C++dll(我没有源代码(。

DLL 具有单个函数,该函数返回指向struct的指针。 该struct定义了一系列函数指针,供我的应用程序用作回调。

根据我收到的"文档",我只是通过将指针设置为我自己的回调方法来"注册"我的回调,如下所示:

server->OnConnectionRequest = &myObj.OnConnectionRequest;

但是,我正在尝试在 C# 中实现这一点。 我已经部分成功了。我可以:

  • 加载 DLL;
  • 从函数获取struct*指针;
  • 调用对象上预定义的一些方法。

我不能做的是在对象上设置自己的回调:编译器不抱怨,运行时不抱怨,但回调仍然没有被调用。

我这样定义了委托类型和类(请注意,以前这被定义为结构,它的工作方式并不相同(:

// Original C++ signature from the header:
// void (*OnRemoteConnectionRequest)(void *caller, const char *ip, int &accept);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void OnRemoteConnectionRequestDelegate(IntPtr caller, string ip, ref int accept);
[StructLayout(LayoutKind.Sequential)]
public class RemoteServerPluginI
{
public OnRemoteConnectionRequestDelegate OnRemoteConnectionRequest;
// another dozen callbacks omitted
}

我有一个静态助手来从 dll 检索实例:

public static class RemoteControlPlugin
{
[DllImport("data/remoteplugin.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr GetServerPluginInterface();
private static RemoteServerPluginI _instance = null;
public static RemoteServerPluginI Instance
{
get
{
if (_instance != null)
return _instance;
var ptr = GetServerPluginInterface();
_instance = Marshal.PtrToStructure<RemoteServerPluginI>(ptr);
if (_instance == null)
throw new InvalidOperationException("Could not obtain the server instance");
return _instance;
}
}
}

最后,这是我用来注册回调的方式:

public class CallBacks
{
public CallBacks(RemoteServerPluginI server)
{
server.OnRemoteConnectionRequest = this.OnRemoteConnectionRequest;
}
public void OnRemoteConnectionRequest(IntPtr caller, string ip, ref int accept)
{
Console.WriteLine($"Remote connection request from {ip}");
// I try to force a reject to see an error on the client,
// but the client always connects successfully, implying
// we never get to run this
accept = 0;
}
}
static void Main()
{
var cb = new Callbacks(RemoteControlPlugin.Instance);
RemoteControlPlugin.Instance.StartServer();
}

然而,当我使用客户端应用程序尝试连接到我的服务器时,我的回调永远不会运行。如您所见,在我的回调中,我拒绝了连接,因此客户端应该退出并显示错误,但事实并非如此。

我做错了什么?

这个:

_instance = Marshal.PtrToStructure<RemoteServerPluginI>(ptr);

将创建RemoteServerPluginI的副本,因此您将处理该副本。 显然是错误的。

使用Marshal.WriteIntPtr()直接写入ptr,例如:

Marshal.WriteIntPtr(remoteServerPluginIPtr, 0, Marshal.GetFunctionPointerForDelegate(OnRemoteConnectionRequest));

在哪里,您应该将委托指针的偏移量放在struct中,而不是0

那么你没有向我们展示回调的 C 签名......也许你在那里也犯了一些错误。

正如 Voigt 所写,另一个非常重要的事情是,委托必须在本机库可以使用它的所有时间内保持活动状态。执行此操作的标准方法是将其放在对象的字段/属性中,然后确保使对象保持活动状态(例如保留对它的引用(。您正在用class RemoteServerPluginI执行此操作.另一种方法是GCHandle.Alloc(yourdelegate, GCHandleType.Normal),然后在确定本机代码永远不会调用它时GCHandle.Free()

一些简单的示例代码。

C面:

extern "C"
{
typedef struct _RemoteServerPluginI
{
void(*OnRemoteConnectionRequest)(void *caller, wchar_t *ip, int *accept);
void(*StartServer)(void);
} RemoteServerPluginI;
void StartServer();
RemoteServerPluginI _callbacks = { NULL, StartServer };
void StartServer()
{
int accept = 0;
_callbacks.OnRemoteConnectionRequest(NULL, L"127.0.0.1", &accept);
wprintf(L"Accept: %d", accept);
}
__declspec(dllexport) RemoteServerPluginI* GetServerPluginInterface()
{
return &_callbacks;
}
}

C# 端:

[DllImport("CPlusPlusSide.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr GetServerPluginInterface();
public static void RemoteConnectionRequestTest(IntPtr caller, string ip, ref int accept)
{
Console.WriteLine("C#: ip = {0}", ip);
accept = 1;
}
public class Callbacks
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void OnRemoteConnectionRequestDelegate(IntPtr caller, [MarshalAs(UnmanagedType.LPWStr)]string ip, ref int accept);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void StartServerDelegate();
public OnRemoteConnectionRequestDelegate RemoteConnectionRequest { get; set; }
public StartServerDelegate StartServer { get; set; }
}

然后:

IntPtr rsp = GetServerPluginInterface();
var callbacks = new Callbacks
{
RemoteConnectionRequest = RemoteConnectionRequestTest
};
Marshal.WriteIntPtr(rsp, 0, Marshal.GetFunctionPointerForDelegate(callbacks.RemoteConnectionRequest));
callbacks.StartServer = Marshal.GetDelegateForFunctionPointer<Callbacks.StartServerDelegate>(Marshal.ReadIntPtr(rsp, IntPtr.Size));
callbacks.StartServer();

请注意,在您的示例中,StartServer是包含在RemoteServerPluginIC 结构中的委托。因此,我们必须使用Marshal.ReadIntPtr检索其值,并为其创建一个 .NET 委托。请注意使用GC.KeepAlive()来确保对象在代码中的某个点之前保持活动状态。另一种常见的方法是使用static变量(static变量的生命周期直到程序结束(

封装各种Marshal的示例:

public class Callbacks
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void OnRemoteConnectionRequestDelegate(IntPtr caller, [MarshalAs(UnmanagedType.LPWStr)]string ip, ref int accept);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void StartServerDelegate();
private IntPtr ptr;
public static implicit operator Callbacks(IntPtr ptr)
{
return new Callbacks(ptr);
}
public Callbacks(IntPtr ptr)
{
this.ptr = ptr;
{
IntPtr del = Marshal.ReadIntPtr(ptr, 0);
if (del != IntPtr.Zero)
{
remoteConnectionRequest = Marshal.GetDelegateForFunctionPointer<OnRemoteConnectionRequestDelegate>(del);
}
}
{
IntPtr del = Marshal.ReadIntPtr(ptr, IntPtr.Size);
if (del != IntPtr.Zero)
{
startServer = Marshal.GetDelegateForFunctionPointer<StartServerDelegate>(del);
}
}
}
private OnRemoteConnectionRequestDelegate remoteConnectionRequest;
private StartServerDelegate startServer;
public OnRemoteConnectionRequestDelegate RemoteConnectionRequest
{
get => remoteConnectionRequest;
set
{
if (value != remoteConnectionRequest)
{
remoteConnectionRequest = value;
Marshal.WriteIntPtr(ptr, 0, remoteConnectionRequest != null ? Marshal.GetFunctionPointerForDelegate(remoteConnectionRequest) : IntPtr.Zero);
}
}
}
public StartServerDelegate StartServer
{
get => startServer;
set
{
if (value != startServer)
{
startServer = value;
Marshal.WriteIntPtr(ptr, IntPtr.Size, startServer != null ? Marshal.GetFunctionPointerForDelegate(startServer) : IntPtr.Zero);
}
}
}
}

然后

Callbacks callbacks = GetServerPluginInterface();
callbacks.RemoteConnectionRequest = RemoteConnectionRequestTest;
callbacks.StartServer();
while (true)
{
}

请注意,然后我会使所有内容都强类型化,完全隐藏IntPtr

[DllImport("CPlusPlusSide.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern CallbacksPtr GetServerPluginInterface();
[StructLayout(LayoutKind.Sequential)]
public struct CallbacksPtr
{
public IntPtr Ptr;
}
public class Callbacks
{
public static implicit operator Callbacks(CallbacksPtr ptr)
{
return new Callbacks(ptr.Ptr);
}
private Callbacks(IntPtr ptr)
{
...
}

添加一个CallbacksPtr,该是可以隐式转换为完整Callbacks对象的IntPtr填充程序。