C#调用C++的Dll(参数和返回值為char* TCHAR*)--Donnie2016,写的很好!转下

想要在C#和C++之间进行字符串传递会涉及到两件事情:

1.C#的string和C++的字符串首指针要怎么对应.  

2.字符串分为ANSI和UNICODE.


C++ 头文件接口:

[cpp]  view plain  copy
  1. //FilePolice.h  
  2.   
  3. //參數和返回值為Ansi  
  4. extern "C" __declspec(dllexportchar* __stdcall EncryptString(char* in_string);  
  5. //參數和返回值為Unicode  
  6. extern "C" __declspec(dllexportTCHAR* __stdcall EncryptStringW(TCHAR* in_string);  
  7. //參數和返回值為int  
  8. extern "C" __declspec(dllexportint __stdcall Sum(int a, int b);  

C++ 实现部分:

[cpp]  view plain  copy
  1. // FilePolice.cpp   
  2.   
  3. #include "stdafx.h"  
  4. #include "FilePolice.h"    
  5.   
  6. TCHAR* __stdcall EncryptStringW(TCHAR* in_string)  
  7. {  
  8.     return in_string;  
  9. }  
  10.   
  11. char* __stdcall EncryptString(char* in_string)  
  12. {  
  13.     return in_string;  
  14. }  
  15.   
  16. int __stdcall Sum(int a, int b)  
  17. {  
  18.     return a + b;  
  19. }  

C# 调用部分:

[csharp]  view plain  copy
  1. class Program  
  2. {  
  3.     [DllImport("FilePolice")]  
  4.     public static extern int Sum(int a, int b);  
  5.   
  6.     [DllImport("FilePolice", CallingConvention = CallingConvention.Cdecl)]  
  7.     [DllImport("FilePolice", CallingConvention = CallingConvention.StdCall)]  
  8.     UnmanagedType.LPStr 為 ANSI  
  9.     UnmanagedType.LPWStr 為 Unicode  
  10.     [DllImport("FilePolice", CharSet = CharSet.Unicode)]  
  11.     public static extern IntPtr EncryptStringW([MarshalAs(UnmanagedType.LPWStr)]string inString);  
  12.   
  13.     [DllImport("FilePolice", CharSet = CharSet.Ansi)]  
  14.     public static extern IntPtr EncryptString([MarshalAs(UnmanagedType.LPStr)]string inString);  
  15.   
  16.     static void Main(string[] args)  
  17.     {  
  18.         int result = Sum(1, 2);  
  19.         Console.WriteLine(result.ToString());  
  20.   
  21.         //Unicode  
  22.         IntPtr ip = EncryptStringW("Hello 您好.");  
  23.         string strIP = Marshal.PtrToStringUni(ip);  
  24.         Console.WriteLine(strIP);  
  25.   
  26.         //Ansi  
  27.         ip = EncryptString("Hello 您好.");  
  28.         strIP = Marshal.PtrToStringAnsi(ip);  
  29.         Console.WriteLine(strIP);  
  30.   
  31.         Console.ReadLine();  
  32.     }  
  33. }  

为了C#能方便调用,在C++中特别将调用方式设置为:__stdcall . (关于调用方式的详细说明,请进 传送门). 否则需要在C#里指定 [DllImport("FilePolice", CallingConvention = CallingConvention.Cdecl)].

另外,由于我们的字符串中会使用到中文,所以一般使用Unicode的方式进行传递.


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值