簡體   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