将 unsigned char 值从 C++ dll 返回到 C# 时出现问题
Problem returning unsigned char value from C++ dll to C#
在下面的示例中,我尝试通过将值传递给 C++ dll 和 return 单个字符串来连接两个无符号字符(这是要求)。我得到的输出不正确。
C#:
using System;
using System.Runtime.InteropServices;
using System.Text;
class HelloWorld
{
[DllImport("cpp_func.dll")]
public static extern IntPtr concat_fun(byte[] a,byte[] b, int c, int d);
static void Main()
{
int x,y;
IntPtr return_value;
string hello = "hello", world = "world", final;
byte[] hel = Encoding.ASCII.GetBytes(hello);
byte[] wor = Encoding.ASCII.GetBytes(world);
x = hel.Length;
y = wor.Length;
return_value = concat_fun(hel, wor, hel.Length, wor.Length);
final = Marshal.PtrToStringAuto(return_value);
Console.WriteLine("Concatenated string:" +final);
Console.Read();
}
}
我将它们声明为 byte[],因为这就是本机类型 uint8_t 在 .NET 中的表示方式 (https://docs.microsoft.com/en-us/dotnet/standard/native-interop/type-marshaling)
我已将两个字节数组及其长度作为参数传递。
C++:
_declspec(dllexport) unsigned char * concat_fun(unsigned char a[], unsigned char b[], int d, int e) {
int i, ind = 0;
unsigned char c[20];
for (i = 0; i < d; i++) {
c[ind] = a[i];
ind++;
}
for (i = 0; i < e; i++) {
c[ind] = b[i];
ind++;
}
return c;
}
我得到的输出是这样的:
Concatenated string:????????????????
如何获取连接后的字符串?
注意:将输入作为 dll 函数参数的无符号字符是一项要求
我知道我在这里犯了一些小错误,因为我只是一个初学者。
c数组的内存是在concat_fun函数中分配的,并且有这个函数的作用域和生命周期,所以当你离开函数体时,内存就会被释放。
尝试在调用函数 Main 中分配 c 数组或使用动态内存分配:new/delete 或 malloc/free in concat_fun.
在下面的示例中,我尝试通过将值传递给 C++ dll 和 return 单个字符串来连接两个无符号字符(这是要求)。我得到的输出不正确。
C#:
using System;
using System.Runtime.InteropServices;
using System.Text;
class HelloWorld
{
[DllImport("cpp_func.dll")]
public static extern IntPtr concat_fun(byte[] a,byte[] b, int c, int d);
static void Main()
{
int x,y;
IntPtr return_value;
string hello = "hello", world = "world", final;
byte[] hel = Encoding.ASCII.GetBytes(hello);
byte[] wor = Encoding.ASCII.GetBytes(world);
x = hel.Length;
y = wor.Length;
return_value = concat_fun(hel, wor, hel.Length, wor.Length);
final = Marshal.PtrToStringAuto(return_value);
Console.WriteLine("Concatenated string:" +final);
Console.Read();
}
}
我将它们声明为 byte[],因为这就是本机类型 uint8_t 在 .NET 中的表示方式 (https://docs.microsoft.com/en-us/dotnet/standard/native-interop/type-marshaling) 我已将两个字节数组及其长度作为参数传递。
C++:
_declspec(dllexport) unsigned char * concat_fun(unsigned char a[], unsigned char b[], int d, int e) {
int i, ind = 0;
unsigned char c[20];
for (i = 0; i < d; i++) {
c[ind] = a[i];
ind++;
}
for (i = 0; i < e; i++) {
c[ind] = b[i];
ind++;
}
return c;
}
我得到的输出是这样的:
Concatenated string:????????????????
如何获取连接后的字符串? 注意:将输入作为 dll 函数参数的无符号字符是一项要求 我知道我在这里犯了一些小错误,因为我只是一个初学者。
c数组的内存是在concat_fun函数中分配的,并且有这个函数的作用域和生命周期,所以当你离开函数体时,内存就会被释放。 尝试在调用函数 Main 中分配 c 数组或使用动态内存分配:new/delete 或 malloc/free in concat_fun.