c#调用c++库函数

如果是非托管的,就用DllImport,举例  
  using System;  
  using System.Runtime.InteropServices;  
  class MainApp  
  [DllImport("Kernel32")] //读取动态库文件  
  public static extern int GetProcAddress(int handle, String funcname);  

  给你讲一下我的经验:  
  首先 你在C#中调用的 是C++ 写的一个动态库。比如Kernel32.dll 中的 函数;  
  这个函数用C++写 有如下要求:  
1、 必须为全局函数  
2、 函数参数 必须为基本类型,也就是C++ 和C#都有的类型,否则你在public static extern int GetProcAddress(int handle, String funcname);  
  这里没有办法声明。 其余的 没什么了;  


先前用VC写的程序生成的DLL,C#里能够调用么?  
可以的话,在VC里传入参数为CString,而C#里是string,怎么传参数呢?  

再者就是问,用VC写的DLL如果是一个导出类,而不是函数接口,C#里可以直接调用么?  
第一个问题我遇到过, 可用如下方法解决:  

  VC++ 中为: int Set(char** str,int n); //将 String 改成 char** , C# 中没有与String对应的类型  
  C# 中为: int Set(ref string str,int n);  
   
  VC++ 中的 BOOL 类型对应 C# 中的 System.Int32 类型, 建议改动一下参数类型吧.

第二个问题,生成的DLL里的函数在一个类里面,这样的话在C#里需要实例化那个类么?怎么做  
比如说,类solution里有函数int getch(int a);  
我怎么调用这个getch函数??  

建议在C++中另外写个函数封装一下, 如:  
  int Dllgetch(int a)  
{  
  solution st = //实例化 类solution  
  return st.getch(a);  
}  
这个 Dllgetch(int a) 就可以提取出来供 C# 调用.
你的方法可以,我也解决了  
将CString 改成了LPCTSTR  
BOOL在C#中对应的是Boolean

原文地址:https://www.cnblogs.com/marblemm/p/7804323.html