C#调用C++封装dll库方法

一、调用步骤
1、准备好C++dll库;
2、将dll库放入exe目录下,或放在某个固定的文件目录下;
3、使用.NET的Interop机制引入C++dll到C#程序中,声明接口函数,例:

[DllImport("Kernel32")]
public static extern int WritePrivateProfileString(string Section, string Key, string Value, string FilePath);
        [DllImport("C:\\Users\\conglin\\AppData\\Roaming\\ShuxiangTech\\LTShiyiCommon\\cache\\updatedll\\CryptEnDe.dll", EntryPoint = "CFB_AESEncryptStr_BASE64")]
public static extern void CFB_AESEncryptStr_BASE64(string key, string iv, string cipherText, StringBuilder outstr);
        [DllImport("C:\\Users\\conglin\\AppData\\Roaming\\ShuxiangTech\\LTShiyiCommon\\cache\\updatedll\\CryptEnDe.dll", EntryPoint = "CFB_AESDecryptStr_BASE64")]
public static extern void CFB_AESDecryptStr_BASE64(string key, string iv, string cipherText, StringBuilder outstr);

其中声明的函数名为dll中的接口名,DllImport中的第一个参数必须为常量
二、注意事项
1、C++封装的接口必须以全局函数形式封装,否则会出现“无法找到入口点”错误,例如:

#define   DLL_API   __declspec(dllexport)
extern "C" DLL_API void CFB_AESEncryptStr_BASE64(const char *key,char *iv,const char *plainText,char *coutstr);

2、注意C#与C++之间数据类型的对应关系,比如
DLL 需传入char *类型

[DllImport(“MyDLL.dll")] 
//传入值
public static extern int mySum (string  astr1,string bstr1); 
//DLL中申明 
extern “C” __declspec(dllexport)  int WINAPI mySum(char * astr2,char *bstr2) 
{ 
   //改变astr2bstr 2  ,astr1 bstr1不会被改变
   return a+b; 
}

DLL 需传出char *类型

[DllImport(“MyDLL.dll")] 
// 传出值
public static extern int mySum (StringBuilder abuf, StringBuilder bbuf ); 
//DLL中申明 
extern “C” __declspec(dllexport)  int WINAPI mySum(char * astr,char *bstr) 
{ 
   //传出char * 改变astr bstr -->abuf, bbuf可以被改变
   return a+b; 
} 

类型对应关系应用可以参考http://blog.csdn.net/hbqhdlc/article/details/6843650

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值