c#调用c++的dll

制作c++的dll

// MyCppDll.cpp : 定义 DLL 应用程序的导出函数。

// 这一句必须
#include "stdafx.h"
// 导入自己想要的头文件
#include <windows.h>

// 为函数加入以下声明即可导出:extern "C" extern __declspec(dllexport) 
//	另外,加入以上声明后函數調用約定默认为“Cdecl”,若要强制指定为,请在函数的返回类型之后加入“__stdcall”关键字
extern "C" extern __declspec(dllexport)  LPCWSTR __stdcall Hello(LPCWSTR lpTitle,LPCWSTR lpContent)
{
	MessageBox(NULL,lpContent,lpTitle,0);
	return lpContent;
}





// 定义 DLL 应用程序的入口点。
// 比如当dll刚被载入至内存或卸载时可以做一些事
BOOL APIENTRY DllMain( HMODULE hModule,
	DWORD  ul_reason_for_call,
	LPVOID lpReserved
	)
{
	switch (ul_reason_for_call)
	{
	case DLL_PROCESS_ATTACH:
		Hello(L"",L"DLL_PROCESS_ATTACH");
		break;
	case DLL_THREAD_ATTACH:
		Hello(L"",L"DLL_THREAD_ATTACH");
		break;
	case DLL_THREAD_DETACH:
		Hello(L"",L"DLL_THREAD_DETACH");
		break;
	case DLL_PROCESS_DETACH:
		Hello(L"",L"DLL_PROCESS_DETACH");
		break;
	}

	return TRUE;
}




写c#

using System;
using System.Runtime.InteropServices;


namespace MyCsharpConsoleApplication
{
    class Program
    {
        [DllImport("MyCppDll", CallingConvention = CallingConvention.StdCall)]
        extern static string Hello(string title, string content);

        static void Main()
        {
            var ret = Hello(@"hello你好".ToAnsi(), @"theraphy大叮当".ToAnsi());
            Console.WriteLine(ret);
        }
    }

    static class Helper
    {
        /// <summary>
        /// 将Unicode字符串转换成多字节字符串
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string ToAnsi(this string content)
        {
            return System.Text.Encoding.Default.GetString(System.Text.Encoding.Unicode.GetBytes(content));
        }
    }
}


也可以直接声明Unicode编码传递

using System;
using System.Runtime.InteropServices;


namespace MyCsharpConsoleApplication
{
    class Program
    {
        [DllImport("MyCppDll", CallingConvention = CallingConvention.StdCall,CharSet = CharSet.Unicode)]
        extern static string Hello(string title, string content);

        static void Main()
        {
            var ret = Hello(@"hello你好", @"theraphy大叮当");
            Console.WriteLine(ret);
        }
    }
}



源码下载

posted @ 2011-12-06 09:50  beta2013  阅读(162)  评论(0编辑  收藏  举报