【技術資料】在C#調用C的DLL函數中,字符串[寬字符/Unicode]的傳入和傳出

using System;
using System.Runtime.InteropServices;
using System.Text;

namespace TESTDLL
{
    class Program
    {
        static void Main(string[] args)
        {
            //向C++提供的參數
            string inputString = "CS Call C Point Dll!哈哈哈";

            //返回的數據,Byte數據,預先分配內存空間
            Byte[] bPara = new Byte[100];

            //調用C++中的函數
            IntPtr outputPointer = MyTest(ref bPara[0], inputString);

            //將分配的內存中的數據轉換爲字符串
            string outputString = UnicodeEncoding.Unicode.GetString(bPara);

            //讀出返回的指針中的數據,其實就是預先分配地址中的數據
            string outputString2 = Marshal.PtrToStringUni(outputPointer);

            Console.WriteLine("源字符串:");
            Console.WriteLine(inputString);

            Console.WriteLine("傳出值:");
            Console.WriteLine(outputString);

            Console.WriteLine("返回值:");
            Console.WriteLine(outputString2);

            Console.ReadLine();
        }

        [DllImport("CDLL.dll", EntryPoint = "MyTest", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
        public static extern IntPtr MyTest(ref Byte refOutputBytes, String inputString);
    }
}

C++源代碼

#include "pch.h"
#include <string>
using namespace std;

//函數聲明
extern"C" __declspec(dllexport) WCHAR* MyTest(WCHAR* dest, WCHAR* sour)
{
	//新建內容
	wstring myWstring = L"收到消息:";
	
	//處理內容
	myWstring.append(sour);
	
	//準備返回數據
	const WCHAR* temp = myWstring.c_str();
	for (size_t i = 0; i < wcslen(temp); i++)
	{
		dest[i] = temp[i];
	}

	//返回
	return dest;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章