【发布时间】:2019-04-03 06:45:52
【问题描述】:
我需要使用一个现有的 3rd 方 API,它带有一个 *.h 和一个 *.dll 文件来将数据加载到 R 中。dll 提供的函数不能直接调用,所以我需要将它们包装起来调用它们来自 R。为了熟悉这一点,我制作了一个小示例 dll(基于 MINGW 页面 here 的 HOWTO,我已将文件的源代码放在帖子末尾)。其中只有一个函数可以将整数输入加倍。我可以很好地编译 dll,也可以在 exe 文件中使用它,所以它可以正常工作。这是在 Windows 10 上。
我不确定如何在 R 中正确使用它。我创建了一个包(名为 testwithdll2 ),将头文件和 dll 与包装函数一起放在“src”中。当我尝试编译包时,我收到了带有未定义引用的以下错误消息:
C:/Rtools/mingw_64/bin/gcc -I"C:/PROGRA~1/R/R-35~1.1/include" -DNDEBUG
-O2 -Wall -std=gnu99 -mtune=generic -c mydouble_c.c -o mydouble_c.o
C:/Rtools/mingw_64/bin/gcc -shared -s -static-libgcc -o testwithdll2.dll
tmp.def mydouble_c.o -LC:/PROGRA~1/R/R-35~1.1/bin/x64 -lR
mydouble_c.o:mydouble_c.c:(.text+0xc): undefined reference to `__imp_timestwo'
collect2.exe: error: ld returned 1 exit status
非常感谢任何关于可能出错的指针。
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 timestwo(int x);
#ifdef __cplusplus
}
#endif
#endif // EXAMPLE_DLL_H
example_dll.cpp:
#include <stdio.h>
#include "example_dll.h"
int timestwo(int x)
{
return 2 * x;
}
mydouble.c(在r包的src文件夹中):
#include "example_dll.h"
void mydouble(int* a){
*a = timestwo(*a);
}
timestwo.R(包装函数,在 R 文件夹中):
#' @useDynLib testwithdll2 mydouble
#' @export
timestwo <- function(n){
.C("mydouble",n )
n
}
【问题讨论】: