C++与C#的数据传递与类型转换

一、数据传递方法

1.基本数据类型的传递

  函数参数和返回值可以是C#和C++的各种基本数据类型,如int, float, double, char(注意不是char*)等。
  示例:
  C#代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using  System;
using  System.Text;
using  System.Runtime.InteropServices;
 
class  Program
{
     [DllImport( @"E:\Projects\testdll\debug\testdll.dll" )]
     public static  extern int  testfunc( int a, float  b, double  c, char d);
 
     static void  Main( string [] args)
     {
         int a = 1;
         float b = 12;
         double c = 12.34;
         char d =  'A' ;
         testfunc(a,b,c,d);
         Console.ReadKey();
     }
}

  C++代码:

1
2
3
4
5
6
7
8
9
10
11
12
<pre  class = "brush:cpp" >#include <iostream>
using namespace  std;
 
extern "C"
{
  _declspec( dllexport ) int  __stdcall testfunc( int a, float  b, double  c, char d)
  {
   cout<<a<< ", " <<b<< ", " <<c<< ", " <<d<<endl;
   return 0;
  }
}
</pre>

2.向DLL传入字符串

  C#中使用string定义字符串,将字符串对象名传给DLL。
  注意:在DLL中更改字符串的值,C#中的值也会改变。
  缺点:无法改变字符串的长度,建议使用第3种方法。
  C#代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using  System;
using  System.Text;
using  System.Runtime.InteropServices;
 
class  Program
{
     [DllImport( @"E:\Projects\testdll\debug\testdll.dll" )]
     public static  extern int  testfunc( string a);
 
     static void  Main( string [] args)
     {
         string a= "Hello World!" ;
         testfunc(a);
         Console.ReadKey();
     }
}

  C++代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace  std;
 
extern "C"
{
  _declspec( dllexport ) int  __stdcall testfunc( char * astr)
  {
   cout<<astr<<endl;
   *astr= 'A' ; //更改字符串的数据
   cout<<astr<<endl;
   return 0;
  }
}

3.DLL传出字符串

  C#中使用StringBuilder对象创建变长数组,并设置StringBuilder的Capacity为数组最大长度。将此对象名传递给DLL,使用char*接收。
  C#代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using  System;
using  System.Text;
using  System.Runtime.InteropServices;
 
class  Program
{
     [DllImport( @"E:\Projects\testdll\debug\testdll.dll" )]
     public static  extern int  testfunc(StringBuilder abuf);
 
     static void  Main( string [] args)
     {
         StringBuilder abuf= new StringBuilder();
         abuf.Capacity = 100; //设置字符串最大长度
         testfunc(abuf);
         Console.ReadKey();
     }
     
}

  C++代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace  std;
 
extern "C"
{
  _declspec( dllexport ) int  __stdcall testfunc( char * astr)
  {
   *astr++= 'a' ;
   *astr++= 'b' ; //C#中abuf随astr改变
   *astr= '\0' ;
 
   return 0;
  }
}

4.DLL传递结构体(需要在C#中重新定义,不推荐使用)

  C#中使用StructLayout重新定义需要使用的结构体。
  注意:在DLL改变结构体成员的值,C#中随之改变。
  C#代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
using  System;
using  System.Text;
using  System.Runtime.InteropServices;
 
[StructLayout(LayoutKind.Sequential)]
public  struct  Point
{
     public double  x;
     public double  y;
}
 
class Program
{
     [DllImport( @"E:\Projects\testdll\debug\testdll.dll" )]
     public static  extern int  testfunc(Point p);
 
     static void  Main( string [] args)
     {
         Point p;
         p.x = 12.34;
         p.y = 43.21;
         testfunc(p);
         Console.ReadKey();
     }   
}

C++代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace  std;
 
struct Point
{
     double x;
     double y;
};
 
extern "C"
{
  _declspec( dllexport ) int  __stdcall testfunc(Point p)
  {
   cout<<p.x<< ", " <<p.y<<endl;
   return 0;
  }
}

5.从C++传出字符串


C++代码:
  1. #ifndef RGB_IHS_C_ADAPTER
  2. #define RGB_IHS_C_ADAPTER
  3. typedef char * (__stdcall* StringHelperCallback)( const char *);
  4. static StringHelperCallback g_csharp_string_callback = NULL;
  5. extern "C" __declspec(dllexport) void RegisterStringCallback(StringHelperCallback callback) {
  6. g_csharp_string_callback = callback;
  7. }
  8. extern "C" __declspec(dllexport) int ExcuteAlgo(const TCHAR* m_strRealpath,
  9. const TCHAR* m_strClassPath,
  10. const char* m_tsReal ,
  11. const char* m_tsclass,
  12. const TCHAR* m_tsRealClassName,
  13. const char*m_tsClassName,
  14. char** fileInfo,/*数据返回,指向C#用委托开辟的内存*/
  15. SysAlgo::stAlgoErr* err,
  16. pProgressFunc pProg,void* pParams);
  17. #endif

C#代码:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Runtime.InteropServices;
  5. namespace AccuracyAnalysis
  6. {
  7. public delegate int ProgressCallback(double dbPos, string pszMessage, IntPtr pArgs);
  8. public struct stAtomDataInfo
  9. {
  10. public string m_strRealpath;
  11. public string m_strClassPath;
  12. public string m_tsReal;
  13. public string m_tsclass;
  14. public string m_tsRealClassName;
  15. public string m_tsClassName;
  16. public string fileInfo;
  17. public stAlgoErr err;
  18. public ProgressCallback pProg;
  19. public IntPtr pParams;
  20. }
  21. public struct stAlgoErr
  22. {
  23. private int m_ErrCode;
  24. private string m_ErrMsg;
  25. public stAlgoErr(int errCode, string errMsg)
  26. {
  27. m_ErrCode = errCode;
  28. m_ErrMsg = errMsg;
  29. }
  30. public int GetErrCode()
  31. {
  32. return m_ErrCode;
  33. }
  34. public string GetErrMsg()
  35. {
  36. return m_ErrMsg;
  37. }
  38. public void SetErrCodeAndMsg(int errCode, string errMsg)
  39. {
  40. m_ErrCode = errCode;
  41. m_ErrMsg = errMsg;
  42. }
  43. }
  44. class Algo
  45. {
  46. #region 本段代码可放在其他位置,但保证系统启动后能初始化
  47. static protected StringHelper swigStringHelper = new StringHelper();
  48. protected class StringHelper
  49. {
  50. public delegate string StringDelegate(string message);
  51. static StringDelegate stringDelegate = new StringDelegate(CreateString);
  52. [ DllImport("ImgClassPostPA.dll", EntryPoint = "RegisterStringCallback", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
  53. public static extern void RegisterStringCallback(StringDelegate stringDelegate);
  54. static string CreateString(string cString)
  55. {
  56. return cString;
  57. }
  58. static StringHelper()
  59. {
  60. RegisterStringCallback(stringDelegate);
  61. }
  62. }
  63. #endregion
  64. #region 算法调用
  65. [ DllImport("ImgClassPostPA.dll", EntryPoint = "ExcuteAlgo", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
  66. public static extern int ExcuteAlgo(string m_strRealpath, string m_strClassPath, string m_tsReal, string m_tsclass,
  67. string m_tsRealClassName, string m_tsClassName, ref string fileInfo, ref stAlgoErr err, ProgressCallback pProg, IntPtr pParams);
  68. #endregion
  69. }
  70. }




二、C++与C#的基本类型对照:




//c++:HANDLE(void   *)       ----   c#:System.IntPtr  

//c++:Byte(unsigned   char)   ----    c#:System.Byte 
        
//c++:SHORT(short)           ----    c#:System.Int16   
      
//c++:WORD(unsigned short) ---  c#:System.UInt16 
       
//c++:INT(int)                 ----    c#:System.Int16     

//c++:INT(int)                  ----    c#:System.Int32    

//c++:UINT(unsigned int)  ----    c#:System.UInt16  
      
//c++:UINT(unsigned int) ----    c#:System.UInt32   
     
//c++:LONG(long)            ----    c#:System.Int32    
     
//c++:ULONG(unsigned long) --   c#:System.UInt32 
        
//c++:DWORD(unsigned long) --  c#:System.UInt32 
        
//c++:DECIMAL         ----    c#:System.Decimal        
 
//c++:BOOL(long)        ----    c#:System.Boolean     
    
//c++:CHAR(char)       ----    c#:System.Char  
       
//c++:LPSTR(char *)      ----    c#:System.String      
   
//c++:LPWSTR(wchar_t *)  ----    c#:System.String  
       
//c++:LPCSTR(const char *)  ---   c#:System.String  
       
//c++:LPCWSTR(const wchar_t *) ---   c#:System.String     

//c++:PCAHR(char *)   ----   c#:System.String     
    
//c++:BSTR       ----    c#:System.String       
  
//c++:FLOAT(float)      ----    c#:System.Single        
 
//c++:DOUBLE(double)    ----    c#:System.Double    
     
//c++:VARIANT           ----    c#:System.Object        
 
//c++:PBYTE(byte   *)   ----    c#:System.Byte[]       
  
//c++:BSTR      ----    c#:StringBuilder    
    
//c++:LPCTSTR   ----    c#:StringBuilder  
      
//c++:LPCTSTR   ----    c#:string        

//c++:LPTSTR    ----     c#:[MarshalAs(UnmanagedType.LPTStr)] string  
       
//c++:LPTSTR     ----    c#:StringBuilder 
     
//c++:LPCWSTR   ----    c#:IntPtr        

//c++:BOOL      ----    c#:bool           

//c++:HMODULE   ----    c#:IntPtr        
    
//c++:HINSTANCE ----    c#:IntPtr        
 
//c++:结构体    ----    c#:public struct 结构体{}; 
        
//c++:结构体 **变量名   ----    c#:out 变量名   

//C#中提前申明一个结构体实例化后的变量名      
 
//c++:结构体 &变量名    ----    c#:ref 结构体 变量名      

           
//c++:WORD      ----    c#:ushort        

//c++:DWORD     ----    c#:uint        

//c++:DWORD     ----    c#:int        

//c++:UCHAR     ----    c#:int        

//c++:UCHAR     ----    c#:byte        

//c++:UCHAR*    ----    c#:string      
  
//c++:UCHAR*    ----    c#:IntPtr        

//c++:GUID      ----    c#:Guid        

//c++:Handle    ----    c#:IntPtr        

//c++:HWND      ----    c#:IntPtr        

//c++:DWORD     ----    c#:int        

//c++:COLORREF  ----    c#:uint       
 
//c++:unsigned char     ----    c#:byte      
  
//c++:unsigned char *   ----    c#:ref byte       
 
//c++:unsigned char *   ----     c#:[MarshalAs(UnmanagedType.LPArray)] byte[]      
  
//c++:unsigned char *   ----     c#:[MarshalAs(UnmanagedType.LPArray)] Intptr       

//c++:unsigned char &   ----    c#:ref byte  
      
//c++:unsigned char 变量名      ----    c#:byte 变量名  
      
//c++:unsigned short 变量名    ----   c#:ushort 变量名 
       
//c++:unsigned int 变量名       ----    c#:uint 变量名    
    
//c++:unsigned long 变量名     ----    c#:ulong 变量名 
       
//c++:char 变量名       ----    c#:byte 变量名 
  
//c++中一个字符用一个字节表示,c#中一个字符用两个字节

表示        

//c++:char 数组名[数组大小]     ----     c#:MarshalAs(UnmanagedType.ByValTStr, SizeConst 

= 数组大小)]        
   
//c++:char *            ----    c#:string       
 
//c++:char *            ----    c#:StringBuilder
    
//c++:char *变量名      ----    c#:ref string 变量名       
 
//c++:char *输入变量名  ----    c#:string 输入变量名    
    
//c++:char *输出变量名  ----    c#:[MarshalAs(UnmanagedType.LPStr)] 

StringBuilder 输出变量名      
  
//c++:char **           ----    c#:string     
   
//c++:char **变量名     ----    c#:ref string 变量名      
  
//c++:const char *      ----    c#:string   
     
//c++:char[]            ----    c#:string     
   
//c++:char 变量名[数组大小]     ----     c#:[MarshalAs

(UnmanagedType.ByValTStr,SizeConst=数组大小)] 

public string 变量名;     

//c++:struct 结构体名 *变量名   ----    c#:ref 结构体名 

变量名        

//c++:委托 变量名   ----    c#:委托 变量名    
    
//c++:int       ----    c#:int        

//c++:int       ----    c#:ref int        

//c++:int &     ----    c#:ref int      
  
//c++:int *     ----    c#:ref int      

//C#中调用前需定义int 变量名 = 0;      
  
//c++:*int      ----    c#:IntPtr        

//c++:int32 PIPTR *     ----    c#:int32[]   
     
//c++:float PIPTR *     ----    c#:float[]       
         
//c++:double** 数组名          ----    c#:ref double 数

组名        

//c++:double*[] 数组名          ----    c#:ref double 数

组名        

//c++:long          ----    c#:int        

//c++:ulong         ----    c#:int           
     
//c++:UINT8 *       ----    c#:ref byte      
 
//C#中调用前需定义byte 变量名 = new byte();             

//c++:handle    ----    c#:IntPtr        

//c++:hwnd      ----    c#:IntPtr         
               
//c++:void *    ----    c#:IntPtr          
      
//c++:void * user_obj_param    ----     c#:IntPtr user_obj_param        

//c++:void * 对象名称    ----     c#:([MarshalAs(UnmanagedType.AsAny)]Object 对象

名称                

//c++:char,INT8,SBYTE,CHAR  --  c#:System.SByte  
        
//c++:short, short int, INT16, SHORT      ----    c#:System.Int16        
  
//c++:int, long, long int,INT32, LONG32, BOOL , INT         ----    c#:System.Int32       
   
//c++:__int64,INT64,LONGLONG      --  c#:System.Int64          

//c++:unsigned char, UINT8, UCHAR , BYTE       ----    c#:System.Byte          

//c++:unsigned short, UINT16, USHORT, WORD, 

ATOM, WCHAR , __wchar_t  ----  c#:System.UInt16  

        
//c++:unsigned, unsigned int, UINT32, ULONG32, 

DWORD32, ULONG, DWORD, UINT     
 ----    c#:System.UInt32          

//c++:unsigned __int64, UINT64, DWORDLONG, 

ULONGLONG                            
----    c#:System.UInt64          

//c++:float,FLOAT    --   c#:System.Single          

//c++:double, long double, DOUBLE      ----    c#:System.Double          

//Win32 Types        ----  CLR Type       
           
//Struct需要在C#里重新定义一个Struct    
    
//CallBack回调函数需要封装在一个委托里,delegate 

static extern int FunCallBack(string str);       
 
//unsigned char** ppImage替换成IntPtr ppImage       
 
//int& nWidth替换成ref int nWidth       
 
//int*, int&, 则都可用 ref int 对应      
  
//双针指类型参数,可以用 ref IntPtr       
 
//函数指针使用c++: typedef double (*fun_type1)

(double); 对应 c#:public delegate double  fun_type1

(double);        

//char* 的操作c++: char*; 对应 c#:StringBuilder;      
  
//c#中使用指针:在需要使用指针的地方 加 unsafe        

//unsigned   char对应public   byte    
版权声明:本文为博主原创文章,未经博
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值