4

我在 C++ 中有非托管 dll,它工作正常,我尝试用 C# 重新实现它,但出现以下错误:

System.ArgumentException : 值不在预期范围内

at System.StubHelpers.ObjectMarshaler.ConvertToNative(Object objSrc, IntPtr pDstVariant)  
at Demo.on_session_available(Int32 session_id) in C:\\Users\\Peyma\\Source\\Repos\\FastViewerDataClient\\FastViewerDataClient\\Demo.cs:line 69

ExceptionMethod:8
ConvertToNative
mscorlib,版本=4.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089
System.StubHelpers.ObjectMarshaler
Void ConvertToNative(System.Object,IntPtr)

H结果:-2147024809

来源:mscorlib

C++代码如下:

typedef void(*func_ptr)(
int sId,
unsigned char cId,
const unsigned char* buf,
int len,
void* context);

struct configuration
{
  func_ptr send;
};

struct send_operation
{
  int session_id;
  unsigned char channel_id;
  std::string data;
};

 auto op = new send_operation();
 op->sId = sessionId;
 op->cId = channelId;
 op->data = "Some Text";

 configuration.send(
    sessionId,
    channelId,
    reinterpret_cast<const unsigned char*>(op->data.c_str()),
    op->data.length(),
    op);

然后在 C# 中翻译如下:

[StructLayout(LayoutKind.Sequential)]
public struct Configuration
{
    public Send send { get; set; }
}

[StructLayout(LayoutKind.Sequential)]
public struct send_operation
{
    public int session_id { get; set; }
    public sbyte channel_id { get; set; }
    public string data { get; set; }
};

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void Send(int sessionId, sbyte channelId, sbyte[] buffer, int len, object context);


 var op = new send_operation
        {
            session_id = session_id,
            channel_id = 0,
            data = "This is a test message!!"
        };

        var bytes = Encoding.UTF8.GetBytes(op.data);

        config.send(sessionId, 0, Array.ConvertAll(bytes, Convert.ToSByte), op.data.Length, op);

更新:

public static void on_session_available(int session_id)
{
    WriteOnFile($"Open session id:{session_id}");

    try
    {
        var op = new send_operation
        {
            session_id = session_id,
            channel_id = 0,
            data = "This is a test message!!"
        };


        var bytes = Encoding.UTF8.GetBytes(op.data);

        config.send_data(session_id, op.channel_id, bytes, op.data.Length, op);
    }
    catch (Exception e)
    {
        WriteOnFile($"Error in sending data:{JsonConvert.SerializeObject(e)}");
        if (e.InnerException != null)
        {
            WriteOnFile($"Error in inner sending data:{e.InnerException.Message}");
        }
    }
}
4

2 回答 2

4

一些变化:

C++, std::stringto unsigned char*,因为很难在 C# 中编组它。

struct send_operation
{
    int session_id;
    unsigned char channel_id;
    unsigned char* data;
};

C#, object contextto IntPtr context, 因为send_operation是一个结构体,这将传递装箱的对象而不是结构体数据。

public delegate void Send(int sessionId, sbyte channelId,
    sbyte[] buffer, int len, IntPtr context);

如何通过:

IntPtr ptr = IntPtr.Zero;
try
{
    ptr = Marshal.AllocHGlobal(Marshal.SizeOf(op));
    Marshal.StructureToPtr(op, ptr, false);
    config.send_data(session_id, op.channel_id, bytes, op.data.Length, ptr);
}
finally
{
    Marshal.FreeHGlobal(ptr);
}
于 2019-09-20T06:53:39.337 回答
0

之前让我对这类工作感到困惑的一件事是“打包”/字对齐。

确认 send_operation 的确切大小。

StructLayout在 C# 中指定具有属性的结构的等效包装,所以......

[StructLayout(LayoutKind.Sequential), Pack = 1] // for byte alignment
[StructLayout(LayoutKind.Sequential), Pack = 2] // for word (2 byte) alignment
[StructLayout(LayoutKind.Sequential), Pack = 4] // for native 32 bit (4 byte) alignment

或者如果有必要明确

[StructLayout(LayoutKind.Explicit)]

这需要FieldOffset每个成员的属性

[FieldOffset(0)]  // for 1st member
[FieldOffset(4)]  // 4 bytes from beginning of struct

在 C(++) 和 .Net 之间进行集成时,明确说明结构类型的这一方面总是一个好主意。

于 2019-09-21T02:43:18.290 回答