loadlibrary和C++头文件

loadlibrary and C++ header files

本文关键字:文件 C++ loadlibrary      更新时间:2023-10-16

我写了一些函数,并用C++代码创建了dll;使用了一些C++头文件。但我发现加载库只支持C头文件,我得到了这个错误:

Error using loadlibrary (line 419)
Failed to preprocess the input file.
Output from preprocessor is:LargeBaseConvertorClass.h
C:Program Files (x86)Microsoft Visual Studio 10.0VCINCLUDEeh.h(26) : fatal error    C1189: #error :  "eh.h is only for
C++!"

我不想更改我的代码,也不想使用mex函数。

如何在matlab中使用我的C++dll?(我需要很多)

谢谢。

亚阿里。

我以前做过两件事来处理这个问题。

第一个是围绕C++代码编写一个C包装器。

//foo_c_wrapper.h
#ifndef FOO_C_WRAPPER_H
#define FOO_C_WRAPPER_H
#ifdef __cplusplus
extern "C" {
#endif
typedef void* FOO_HANDLE;//can use a predeclared pointer type instead
FOO_HANDLE init_foo(int a);
void bar(FOO_HANDLE handle);
void destroy_foo(FOO_HANDLE** handle);
//ect
#endif
//foo.hpp
#ifndef FOO_HPP
#define FOO_HPP
class Foo {public: Foo(int); ~Foo(); void bar();}
#ifdef __cplusplus
}
#endif
#endif
//foo_c_wrapper.cpp
#include "foo_c_wrapper.h"
#include "foo.hpp"
extern "C" {
FOO_HANDLE init_foo(int a) {return new Foo(a);}
void bar(FOO_HANLDE handle) {
   Foo* foo = reinterpret_cast<Foo*>(handle);
   foo->bar();
}
void destroy_foo(FOO_HANDLE** handle) {
   Foo** foo = reinterpret_cast<Foo**>(handle);
   delete *foo;
   *foo = NULL;
}
}

另一种选择是按照创建自定义mex文件的方法。不幸的是,这个主题太宽泛了,无法在这里详细介绍,所以我将把"创建一个C++兼容的Mex文件"作为以下链接的摘要:

http://www.mathworks.com/help/matlab/matlab_external/c-mex-file-examples.html#btgcjh1-14

我过去通过创建一些C接口函数来创建和操作C++对象。这样就可以很容易地使用Matlab中的C++代码,而不必修改它。只要标题只有C,如果最终创建了C++对象,Matlab就不会抱怨。

例如,如果你想从Matlab中使用的类是:

class MyClass
{
public:
    double memberFunction();
};

具有头文件be(添加前缀以导出函数):

int createObject();
double callFunction( int object );

让cpp文件类似于:

static std::map<int,MyClass*> mymap;
int createObject()
{
    MyClass* obj = new MyClass();
    int pos = mymap.size();
    mymap[pos] = obj;
    return pos;
}
double callFunction( int obj )
{
    return mymap[obj]->memberFunction();
}

现在,您可以从Matlab创建MyClass对象和访问成员。

您需要传递更多的参数,更好地处理地图内容(检查地图中是否存在对象,如果不存在则返回错误,完成后从地图中删除对象…等等),但这是一般的想法。