2013-04-10 58 views
0

我需要在C程序中使用某些函数。为了测试我定义如下:如何将C DLL加载到C#代码中?

这是我的.h文件:

namespace amt 
{ 
    class AMT_EXPORT FaceRecognition 
    { 
     public: 
      std::string amt_test_string(std::string in); 
    }; 
}; 

这是我的.cpp文件:

#include <memory.h> 
#include <string> 
#include <iostream> 
#include <fstream> 
#include "api_shared.h" 
#include <sys/stat.h> 

using namespace std; 

std::string amt::FaceRecognition::amt_test_string (std::string in) 
{ 
    std::string s="in: "+in; 
    std::cout<<s<<std::endl; 

    return s; 
} 

我想调用的方法是这样的:

const string str = "C:\\minimal.dll"; 
[DllImport(str)] 
public static extern string amt_test_string(string input); 
static void Main(string[] args) 
{ 
    string myinput = "12"; 
    string myoutput = ""; 
    myoutput = amt_test_string(myinput); 
    Console.WriteLine(myoutput); 
    Console.Read(); 

} 

但即时获取错误,说它无法找到名为amt_test_string..why的入口点,为什么呢?我是C btw的新手

回答

3

这不是一个C DLL,这是一个C++ DLL。 C和C++都是而不是是同一种语言。特别是,C++有名称变形,所以导出到DLL的函数名称是装饰

我强烈建议您避免因为这个原因在您的DLL中导入C++。如果仅使用C导出,则符号名称将是可预测的(即,不会依赖于C++编译器如何修饰名称的具体细节),并且不必担心运行时差异,例如C++标准库如何实现std::string

我建议你DLL导出这个样子的:

extern "C" // This says that any functions within the block have C linkage 
{ 

// Input is 'in', output gets stored in the 'out' buffer, which must be 'outSize' 
// bytes long 
void DLLEXPORT amt_FaceRecogniztion_amt_test_string(const char *in, char *out, size_t outSize) 
{ 
    ... 
} 

} 

此接口不依赖于任何特定的库的std::string实施和C#懂得武术char*参数C字符串。但是,内存管理更加复杂,因为您需要找出输出结果有多大的上界并传递适当大小的缓冲区。