【技术资料】在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;
}

交流QQ群:

456197310 PC微信HOOK逆向分析

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

赵庆明老师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值