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;
}