繁体   English   中英

将C#char数组传递给C ++与字节数组不同

[英]Passing C# char array to C++ not same as byte array

在C ++中,

__declspec(dllexport)
    void charArrayTest(void * ptr)
{
    char*c = (char*)ptr;
    c[0] = 97;
    c[1] = 0;
    c[2] = 97;
    c[3] = 0;
}

这适用于C#字节数组:

[DllImport("KutuphaneCL", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern void charArrayTest(byte[] arr);


byte[] tst = new byte[20];
charArrayTest(tst);
Console.WriteLine(tst[0]);
Console.WriteLine(tst[1]);
Console.WriteLine(tst[2]);
Console.WriteLine(tst[3]);
Console.WriteLine(tst[4]);
Console.WriteLine(tst[5]);

输出:

97 0 97 0 0 0

但是当我从C#端尝试char数组时,

[DllImport("KutuphaneCL", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern void charArrayTest(char[] arr);


//simpleCharSingleGPU();
char[] tst = new char[20];
charArrayTest(tst);
Console.WriteLine((int)tst[0]);
Console.WriteLine((int)tst[1]);
Console.WriteLine((int)tst[2]);
Console.WriteLine((int)tst[3]);
Console.WriteLine((int)tst[4]);
Console.WriteLine((int)tst[5]);

它输出零。 我期望非零值,因为每个字符的下半部分或下半部分都在C ++中被更改(除非不将char数组作为原始数组传递)

为什么C#无法将char数组传递为与字节数组相同(我知道char在内存中为2字节,但是这与“我不能在C ++中更改”的情况如何相关)?

使用Visual Studio 2015 Community Edition和最新更新。 双方都针对x64进行了编译。

在C#(不安全的上下文)中,还有类似Marshal.SizeOf(tst[0].GetType())返回“ 1”而sizeof(char)返回“ 2”的怪异事物。

您可以通过这种方式将字符串更改为字节数组

byte[] bytes = Encoding.ASCII.GetBytes(somestring);

并将其传递给c ++函数

暂无
暂无

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

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