動態庫:
//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);
}
}
}