在通过 P/Invoke 获取的 C++ 结构上设置 C# 回调
Set C# callback on a C++ struct obtained via P/Invoke
我正在尝试使用我得到的外部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
是包含在RemoteServerPluginI
C 结构中的委托。因此,我们必须使用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
填充程序。
- sizeof 函数如何在带和不带位字段的结构上工作?(填充)
- 未使用的 asm() 在不受支持的体系结构上的行为
- 复制引用结构上的赋值
- 有了memory_order_relaxed,原子变量的总修改顺序如何在典型体系结构上得到保证
- C 嵌套结构上的 g++ 编译错误
- 结构上溢出的整数加法
- 在通过 P/Invoke 获取的 C++ 结构上设置 C# 回调
- 在包含浮点数的结构上使用 memset()
- 在模板化数据结构上调用 begin() 或 end()
- 在现有数据结构上使用BGL算法需要什么(边和顶点作为矢量<对象*>)?
- boost :: Spirit :: Karma语法:逗号从结构上划定了带有选件属性的输出
- 使用提升库在队列和堆栈数据结构上保存和加载数据时出错
- 所有结构上的奇怪内存位移
- 是在同一体系结构上运行的静态编译的纯标准C 程序可移植
- 在英特尔x86体系结构上使用非AVX指令修改xmm整数寄存器值
- 结构上的内存分配和复制构造函数
- 结构上的 C++ 中的比较器函数
- 用载体建立在苍蝇递归结构上
- 为什么在不同的计算机体系结构上,相同的GCC的编译选项会有所不同
- NUMA体系结构上大(8MB)内存区域的可扩展分配