VS2010里C#调用C++ dll文件(数字及字符串传参)
(2012-07-18 18:23:26)
					
											标签:
																				
                            vs2010cdll接口杂谈 | 
					分类: 学习 | 
			查了一些资料,貌似说.net 3.5 和.net4.0调用c++
dll的方式不用,我没试验过,一直用的VS2010,如果以下方法有人不适用,可能有这方便原因。
    return x+y;  
    class Program  
    {  
     
  static void Main(string[] args)    
     
  {    
     
     
Console.WriteLine("result: " + test.add(-12, 3).ToString());      
     
      string a =
"Hola";      
     
      string b =
"Jose";      
     
      IntPtr p =
test.Suma(a, b);      
     
      string c =
Marshal.PtrToStringAnsi(p);      
     
     
Marshal.FreeHGlobal(p);      
     
     
Console.WriteLine(c);      
     
     
Console.ReadLine();      
     
  }    
    }  
    class test  
    {  
     
  [DllImport("TestDLL.dll", CallingConvention =
CallingConvention.Cdecl)]    
     
  public static extern int add(int i, int
j);    
     
  [DllImport("TestDll.dll", CallingConvention =
CallingConvention.Cdecl)]    
     
  public static extern System.IntPtr Suma(string
a, string b);    
    }  
							
		
						
		
		
		
		
		C++部分 
stdafx.h:
#include "targetver.h"
#define WIN32_LEAN_AND_MEAN  
     
    // Exclude rarely-used stuff
from Windows headers      
// Windows Header Files:
#include <windows.h>
// TODO: reference additional headers your program requires
here
#ifndef LIB_H
#define LIB_H
extern "C" int _declspec(dllexport)add(int x,int y);
   // 声明为C编译、链接方式的外部函数  
extern "C" _declspec(dllexport)  char*
Suma(char* a, char* b); 
#endif
TestDLL.cpp
#include "stdafx.h"
int add(int x,int y)
{
}
char* Suma(char* a, char* b)
{
char* result = (char*)LocalAlloc(LPTR, strlen(a) + strlen(b) +
1);
strcat(result, a);
strcat(result, b);
return result;
}
C#部分:
program.cs
之前在调试的时候虽然结果运行正确,但一直出现错误提示,
“Managed Debugging Assistant 'PInvokeStackImbalance' has
detected a problem in...."
在DLLImport中加入CallingConvention =
CallingConvention.Cdecl就ok了
KEY WORDS:  either
use  on
your C++ function or declare on
your   
__stdcall CallingConvention
= CallingConvention.Cdecl DllImport.
ok,问题解决了
后一篇:5233刷机参考
					
加载中…