编程语言
首页 > 编程语言> > C#调用C++ 类型转换

C#调用C++ 类型转换

作者:互联网

 Marshal 类

msdn:https://docs.microsoft.com/zh-cn/dotnet/api/system.runtime.interopservices.marshal?redirectedfrom=MSDN&view=netframework-4.8#methods

csdn:https://blog.csdn.net/u011555996/article/details/103916426

常用转换:

字符串:

// 创建一个托管字符串
string managedString = "I am a managed String";

// 将托管字符串复制到非托管内存
IntPtr stringPointer = (IntPtr)Marshal.StringToHGlobalAnsi(managedString);

// 将非托管内存复制到托管字符串
string retrievedString = Marshal.PtrToStringAnsi(stringPointer);

// 释放非托管内存
Marshal.FreeHGlobal(stringPointer);

//在释放之前,还可以继续访问
string retrievedString2 = Marshal.PtrToStringAnsi(stringPointer);

Task.Factory.StartNew(() =>
{
    System.Threading.Thread.Sleep(5000);
    //在释放之后,无法访问到
    string retrievedString3 = Marshal.PtrToStringAnsi(stringPointer);
});

数组:

// 创建托管数组
int[] managedArray = { 1, 2, 3, 4 };

// 单个字节非托管内存大小
int size = Marshal.SizeOf(managedArray[0]) * managedArray.Length;

//在非托管内存中分配字节大小
IntPtr intPtr = Marshal.AllocHGlobal(size);

try
{
    // 将数据从托管数组复制到非托管内存指针
    Marshal.Copy(managedArray, 0, intPtr, managedArray.Length);

    //创建新的托管数组
    int[] managedArray2 = new int[managedArray.Length];

    //从非托管内存指针复制到托管数组
    Marshal.Copy(intPtr, managedArray2, 0, managedArray.Length);
}
finally
{
    // 释放以前从进程的非托管内存中分配的内存
    Marshal.FreeHGlobal(intPtr);
}

 

标签:类型转换,string,C#,托管,C++,内存,managedArray,Marshal,stringPointer
来源: https://www.cnblogs.com/kuangxiangnice/p/12365667.html