动态库:
//MyPointDll.h
extern"C" _declspec(dllexport) char* strcpyTest(char* dest,char* sour);
// MyPointDll.cpp : 定义 DLL 应用程序的导出函数。//
#include "stdafx.h"
#include "MyPointDll.h"
char* strcpyTest(char* dest,char* sour)
{
char* temp = dest;
while('\0' != *sour)
{
*dest = *sour;
dest++;
sour++;
}
*dest = '\0';
return temp;
}
C#调用Dll:
using System;
using System.Runtime.InteropServices;
namespace CSCallMyPointDll
{
class Program
{
[DllImport(@"MyPointDll.dll", EntryPoint = "strcpyTest", CallingConvention = CallingConvention.Cdecl/*, CallingConvention = CallingConvention.Cdecl*/)]
public static extern IntPtr strcpyTest(ref byte dest, string sour);
static void Main(string[] args)
{
string strSour = "CS Call C Point Dll!";
Byte[] bPara = new Byte[100]; //新建字节数组
IntPtr pRet = strcpyTest(ref bPara[0], strSour);
string strGet = System.Text.Encoding.Default.GetString(bPara, 0, bPara.Length); //将字节数组转换为字符串
string strRet = Marshal.PtrToStringAnsi(pRet);
Console.WriteLine("源字符串:");
Console.WriteLine(strSour);
Console.WriteLine("传出值:");
Console.WriteLine(strGet);
Console.WriteLine("返回值:");
Console.WriteLine(strRet);
}
}
}