繁体   English   中英

将字节数组从 c++ DLL 传递到 c# 客户端时的随机结果

[英]Random results when passing byte array from c++ DLL to c# client

我正在将字节数组从 function 内部的 c++ DLL 传递到 c# 客户端。 我在 C# 中使用广泛推荐的 IntPtr 指针方法,然后在 C# 客户端中使用 Marshal.Copy 创建字节数组。 当我读取结果数组时,我似乎得到了随机值。 没有传递 DLL 中的实际值。

似乎 IntPnt 指向某个随机的 memory 地址?

这是代码:

C++ DLL

extern "C" __declspec(dllexport) char*  __stdcall passBytes() {
    cout << "\n passBytes DLL code START \n";

    char bytes[] = { 0x07, 0x08 };
    cout << "bytes array size: " << sizeof(bytes) << endl;
    for (int i = 0; i < sizeof(bytes); i++) {
        cout << "byte " << i << " = " << (int)bytes[i] << endl;
    }
    
    char* bptr = bytes;
 
    cout << "\n passBytes DLL code END \n";

    return bptr;
}

C# 客户

namespace sc_client
{
    class Program
    {
        static void Main(string[] args)
        {
           
            const string libname = "C:/work/x64/Release/libMxN.dll";

            [DllImport(libname)]
           
            static extern IntPtr passBytes();
            IntPtr ptr = passBytes();
            byte[] cbytes = new byte[2];
            Marshal.Copy(ptr, cbytes, 0, 2);

            Console.WriteLine("C# client output: ");
            for ( int i = 0; i < cbytes.Length; i++)
            {
                Console.WriteLine("client byte " + i + " = " + (int)cbytes[i]);
            }
        }
    }
}

输出(只是重新启动应用程序 4 次,没有对代码进行任何修改) 1. passBytes DLL code START bytes array size: 2 byte 0 = 7 byte 1 = 8

passBytes DLL 代码结束

C# 客户端 output:客户端字节 0 = 176 客户端字节 1 = 232

2. passBytes DLL code START字节数组大小:2 byte 0 = 7 byte 1 = 8

passBytes DLL code END C# client output: client byte 0 = 144 client byte 1 = 232

3. passBytes DLL code START字节数组大小:2 byte 0 = 7 byte 1 = 8

passBytes DLL code END C# client output: client byte 0 = 176 client byte 1 = 228

您的主要问题似乎是char*数组是在本地声明的,并且在 function 完成后立即消失。 正确执行此操作的一种方法是在堆上分配它,并创建一个单独的Free function。

但是你最好只是传递一个缓冲区。 我不太熟悉 C++,但像这样的东西就是你的 function

extern "C" __declspec(dllexport) void  __stdcall passBytes(char* bytes, int size) {
....

然后在 C# 你像这样使用它

const string libname = "C:/work/x64/Release/libMxN.dll";

[DllImport(libname)]
static extern void passBytes([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)][Out] byte[] bytes, int size);

static void Main(string[] args)
{
    byte[] cbytes = new byte[2];
    passBytes(cbytes, cbytes.Length);

    Console.WriteLine("C# client output: ");
    for ( int i = 0; i < cbytes.Length; i++)
    {
        Console.WriteLine("client byte " + i + " = " + (int)cbytes[i]);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM