出于学习目的,我正在尝试将DLL加载到MATLAB中,该MATLAB调用另一个DLL中定义的函数.我是所有这一切的新手,还没有弄清楚我将如何做到这一点,也没有设法找到任何相关的资源.
我在C中写了一个小DLL,它是这样的:
//example_dll.h
#ifndef EXAMPLE_DLL_H
#define EXAMPLE_DLL_H
#ifdef __cplusplus
extern "C" {
#endif
#ifdef BUILDING_EXAMPLE_DLL
#define EXAMPLE_DLL __declspec(dllexport)
#else
#define EXAMPLE_DLL __declspec(dllimport)
#endif
int EXAMPLE_DLL Double(int x);
#ifdef __cplusplus
}
#endif
#endif // EXAMPLE_DLL_H
和源文件:
//example_dll.cpp
#include
#include "example_dll.h"
int Double(int x)
{
return 2 * x;
}
我使用MinGW w64构建并使用loadlibrary(‘example_dll’)加载到matlab中,没有任何问题.
我现在想要定义这个功能
int Double(int x)
{
return 2 * x;
}
在另一个DLL中,(让我们称之为DLL2)并从我的example_dll中调用该函数.
最简单的方法是什么?
我将很感激一个简短的示例代码(最好是运行时动态链接,不使用模块定义(.def)文件)或链接到互联网上的相关资源.
谢谢!
简单解决方案的解决方案:
我想我得到了解决方案.无论如何它似乎都在起作用.
我创建了一个名为interface_DLL的DLL,我将其加载到MATLAB中,然后在example_dll中调用了我的函数
这里是:
//interface_dll.h
#ifndef INTERFACE_DLL_H
#define INTERFACE_DLL_H
#ifdef __cplusplus
extern "C" {
#endif
#ifdef BUILDING_INTERFACE_DLL
#define INTERFACE_DLL __declspec(dllexport)
#else
#define INTERFACE_DLL __declspec(dllimport)
#endif
int INTERFACE_DLL Quadruple(int x);
#ifdef __cplusplus
}
#endif
#endif // INTERFACE_DLL_H
和源文件:
//interface_dll.cpp
#include
#include
#include "interface_dll.h"
#include "example_dll.h"
int Quadruple(int x)
{
/* get handle to dll */
HINSTANCE hGetProcIDDLL = LoadLibrary("C:\\Users\\uidr0605\\Documents\\ExampleDLL\\example_dll.dll");
/* get pointer to the function in the dll*/
FARPROC lpfnGetProcessID = GetProcAddress(HMODULE (hGetProcIDDLL),"Double");
/*
Define the Function in the DLL for reuse. This is just prototyping the dll's function.
A mock of it. Use "stdcall" for maximum compatibility.
*/
typedef int (__stdcall * pICFUNC)(int);
pICFUNC Double;
Double = pICFUNC(lpfnGetProcessID);
/* The actual call to the function contained in the dll */
int intMyReturnVal = Double(x);
intMyReturnVal = Double(intMyReturnVal);
/* Release the Dll */
FreeLibrary(hGetProcIDDLL);
/* The return val from the dll */
return intMyReturnVal;
}
我从MATLAB加载它如下:
%loadDLL.m
path = 'C:\Path\to\DLL\';
addpath(path);
loadlibrary('interface_dll')
i = 2;
x = calllib('interface_dll', 'Quadruple', i)
我对解决方法的想法是使用中间DLL作为MATLAB和我打算访问的类的DLL之间的接口.
有没有更好的方法呢?
进一步的问题:
任何人都可以解释一下line typedef int(__stdcall * pICFUNC)(int)的重要性;在这里适用?
如果我想在example_dll中的类中调用函数,我需要添加什么或者我需要做些什么更改?
编辑:我将以下代码添加到example_dll头文件中:
class EXAMPLE_DLL MyClass
{
public:
int add2(int);
};
#ifdef __cplusplus
extern "C" {
#endif
MyClass EXAMPLE_DLL *createInstance(){
return new MyClass();
}
void EXAMPLE_DLL destroyInstance(MyClass *ptrMyClass){
delete ptrMyClass;
}
#ifdef __cplusplus
}
#endif