c#调用c++的dll
2011-12-06 09:50
204 查看
制作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); } } }
源码下载
相关文章推荐
- C#调用C/C++ dll
- C#调用c++创建的dll
- 在c#里调用C++的dll时,需要注意的一些问题
- 在C#调用C++的DLL简析(一)——生成非托管dll
- c#程序调用c++编写dll需要注意问题
- C# 中调用C++ DLL (P/Invoke)
- C#调用C++ Dll
- C#调用C++DLL总结
- C#调用C++的DLL 所有数据类型转换方式
- c# 代码调用c++生成的dll过程
- c# 调用 C++ dll
- C#调用C++的dll两种方法(托管与非托管)
- c# 调用 c++ dll 参数为结构体数组指针
- c#调用C++ 写的DLL(带CALLback函数)
- C#调用C++dll
- C#调用C++的DLL搜集整理的所有数据类型转换方式
- C++调用C#的Dll实现Xml读写
- C#调用c++的标准动态链接库dll
- C++通过DLL调用C#代码
- C#调用C++DLL库常见问题