簡體   English   中英

將數組內存文件C ++共享到C#

[英]Sharing array memoryfile C++ to C#

我嘗試根據此示例通過memoryfile c ++將數組共享到c#:通過共享內存將數據從c ++流到c# 工作正常,但我只能從數組中獲取到位置3,另一個位置為0。

創建MemoryFile的C ++

#include <windows.h>
#include <stdio.h>

struct Pair {
    int length;
    int data[10];
};

struct Pair* p;
HANDLE handle;

int dataSend[10]{ 500,33,44,66,2,55,98,7,52,36 };

bool startShare()
{
    try
    {
        handle = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(Pair), L"DataSend");
        p = (struct Pair*) MapViewOfFile(handle, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, sizeof(Pair));
        return true;
    }
    catch (...)
    {
        return false;
    }

}


int main()
{

    if (startShare() == true)
    {
        printf("Memory Create");
        while (true)
        {
            if (p != 0) {


                for (int h = 0; h < 10; h++)
                {
                     p->data[h] = dataSend[h];
                     printf("\n number %d", dataSend[h]);
                }

            }


            else
                puts("create shared memory error");
        }
    }
    if (handle != NULL)
        CloseHandle(handle);
    return 0;
}

我的C#閱讀

public static int[] data = new int[10];
public static MemoryMappedFile mmf;
public static MemoryMappedViewStream mmfvs;

static public bool MemOpen()
{
    try
    {
        mmf = MemoryMappedFile.OpenExisting("DataSend");
        mmfvs = mmf.CreateViewStream();
        return true;
    }
    catch
    {
        return false;
    }

}

public static void Main(string[] args)
{
    while (true)
    {
        if (MemOpen())
        {

            byte[] blen = new byte[4];
            mmfvs.Read(blen, 0, 4);

            byte[] bPosition = new byte[280];
            mmfvs.Read(bPosition, 0, 280);
            Buffer.BlockCopy(bPosition, 0, data, 0, bPosition.Length);

            for (int i = 0; i < data.Length; i++)
            {
                Console.WriteLine(data[i]);
            }

        }
    }

}

工作正常,但我只能從數組中獲取到位置3,另一個位置為0。

更新,代碼現在可以正常工作只是一個細節,我返回一個數組十六進制值示例:52A7E600,但是在我的代碼中,C#獲得的位數如:10300071984,我如何無法在C#側轉換以獲得相同的格式?

要將長值轉換為c#中的十六進制,可以使用:

        long intValue = 10300071984;
        // Convert long value 10300071984 -> 265EEA030 as a hex in a string variable
        string hexValue = intValue.ToString("X"); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM