我正在尝试使用已获得的外部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));
在代替
0
的位置,应将委托指针的偏移量放在struct
中。那么您就没有向我们展示回调的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
,它是IntPtr
的填充程序,可以隐式转换为完整的Callbacks
对象。关于c# - 在通过P/Invoke获得的C++结构上设置C#回调,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50818345/