我想在我的C代码中使用dll文件,但对语法非常困惑。
我的故事:我在Matlab(f(x1,x2)= x1 * x2)中使用" Matlab编码器"我把它翻译成C-Code并生成了一个exe,我可以从终端用参数运行它。现在我生成了一个dll而不是exe并且想要使用dll。
从现在起我无法进行代码解释,我用Google搜索,为我工作。我在http://en.cppreference.com/w/中查找语法,但令我惊讶的是,它甚至没有例如GetProcAddress或LoadLirbary。
以下是我想使用dll的C代码:
#include <stdio.h>
#include <stdlib.h>
/*
* In my dream I would load the dll function here
* with something like Load(mytimes4.dll)
*/
int main(int argc, char *argv[]) {
double x1,x2,myresult;
//Load Arguments from Terminal
sscanf(argv[1], "%lf", &x1);
sscanf(argv[2], "%lf", &x2);
// Use and print the function from mytimes4.dll
myresult = mytimes4(x1,x2);
printf("%3.2f\n",myresult);
return 0;
}
生成dll后,Matlab给了我以下文件夹: "dll-folder" produced by Matlab
有人可以给我一个最简单但完整的代码,可以用我的例子吗?需要什么文件(可能是.def或.exp)?另外,对于使用dll涉及的线的解释,我将不胜感激。或者如果没有,你可能有一些背景知识,使复杂的语法合理。谢谢你提前!
系统信息:Windows 7 Pro 64,Matlab 64 2016b,gcc cygwin 64,eclipse ide。
答案 0 :(得分:0)
通过 thurizas 的链接,我可以解决我的问题。 https://msdn.microsoft.com/en-us/library/windows/desktop/ms686944(v=vs.85).aspx 我从侧面复制了代码。下面你可以看到我的附加评论的代码,在我看来,更清楚地命名。因此,对我来说,初学者可能更容易使用。
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
/*Declaration of the function,contained in dll, as pointer with the arbitrary pointer name
"*MYFUNCTIONPOINTER" (not sure if it has to be in big letters).
In my case the function means simply f(x1,x2) = x1*x2 and is thus as double declared*/
typedef double (*MYFUNCTIONPOINTER)(double, double);
int main() {
HINSTANCE hinstLib;
//"myfunction" is the arbitrary name the function will be called later
MYFUNCTIONPOINTER myfunction;
BOOL fFreeResult, fRunTimeLinkSuccess = FALSE;
//Tell the dll file
hinstLib = LoadLibrary(TEXT("mypersonal.dll"));
if (hinstLib != NULL)
{
/* At this line "myfunction" gets its definition from "MYFUNCTIONPOINTER"
and can be used as any other function.The relevant function in the dll has
to be told here.*/
myfunction = (MYFUNCTIONPOINTER) GetProcAddress(hinstLib, "mydllfunction");
// If the function address is valid, call the function.
if (NULL != myfunction)
{
fRunTimeLinkSuccess = TRUE;
// The function can be used.
double myoutput;
myoutput = myfunction(5,7);
printf("%f\n",myoutput);
getchar();
}
// Free the DLL module.
fFreeResult = FreeLibrary(hinstLib);
}
// If unable to call the DLL function, use an alternative.
if (! fRunTimeLinkSuccess)
printf("Message printed from executable\n");
return 0;
}