1

我正在从我正在编写的 C# 包装器中调用外部 C 库。我正在调用的函数之一是注册回调函数。调用该函数时没有错误,setCallback但是稍后调用回调函数时会出现错误,遗憾的是 C 库未指定。

这是C方法(来自头文件)

DLLExport int setCallbacks(Client handle, void* context, connectionLost* cl,
messageArrived* ma, deliveryComplete* dc);

这是我对该方法的 C# 声明

[DllImport("some.dll", CharSet = CharSet.Auto, ExactSpelling = false, 
CallingConvention = CallingConvention.Cdecl)]
private static extern int setCallbacks(IntPtr client, IntPtr context,
MulticastDelegate connectionLost, MulticastDelegate messageArrived, 
MulticastDelegate messageDelivered);

这些是我的代表

private delegate int ConnectionLostDelegate(IntPtr context, [MarshalAs(UnmanagedType.LPStr)] String cause);
private delegate int MessageArrivedDelegate(IntPtr context, [MarshalAs(UnmanagedType.LPStr)] String title, Int32 titleLength, MessageObject message);
private delegate int MessageDeliveredDelegate(IntPtr context, int deliveryToken);

这就是我调用该方法的方式

ConnectionLostDelegate conLost = new ConnectionLostDelegate(ConnectionLost);
MessageArrivedDelegate mesArr = new MessageArrivedDelegate(MessageArrived);
MessageDeliveredDelegate mesDel = new MessageDeliveredDelegate(MessageDelivered);

result = setCallbacks(client, IntPtr.Zero, conLost, mesArr, mesDel);

这是其中一个回调使用的结构

[StructLayout(LayoutKind.Sequential)]
public class MessageObject
{
    [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 4, ArraySubType = UnmanagedType.U1)]
    public byte[] struct_id;
    Int32 struct_version;
    Int32 payloadlen;
    IntPtr payload;
    Int32 qos;
    Int32 retained;
    Int32 dup;
    Int32 msgid;

    public MessageObject()
    {
        struct_id = Encoding.ASCII.GetBytes("WXYZ");
        struct_version = 0;
        payload = IntPtr.Zero;
    }
}

回调函数的 C 标头如下..

typedef int messageArrived(void* context, char* title, int titleLen, MessageObject* message);

typedef void deliveryComplete(void* context, int token);

typedef void connectionLost(void* context, char* cause);
4

1 回答 1

1

我在 p/invoke 方面没有很多经验,但看起来你应该更正代表的签名以返回 void,它在 c 中是无效的。并且还将 ref 用于指针参数,例如上下文和消息

于 2012-04-13T11:26:23.147 回答