C#源代碼
using System;
using System.Runtime.InteropServices;
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 = System.Text.Encoding.Default.GetString(bPara, 0, bPara.Length); //將字節數組轉換爲字符串
//讀出返回的指針中的數據,其實就是預先分配地址中的數據
string outputString2 = Marshal.PtrToStringAnsi(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)]
public static extern IntPtr MyTest(ref byte refOutputBytes, string inputString);
}
}
C++源代碼
// dllmain.cpp : 定義 DLL 應用程序的入口點。
#include "pch.h"
#include <string>
using namespace std;
//函數聲明
extern"C" __declspec(dllexport) char* MyTest(char* dest, char* sour);
//函數實現
char* MyTest(char* dest, char* sour)
{
char* temp = dest;
while ('\0' != *sour)
{
*dest = *sour;
dest++;
sour++;
}
*dest = '\0';
return temp;
}