【问题标题】:How to wrap 3rd party DLL for use in R?如何包装第 3 方 DLL 以在 R 中使用?
【发布时间】: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
}

【问题讨论】:

    标签: c++ c r


    【解决方案1】:

    我想出了该怎么做。 必须使用具有以下行的 makevars 文件:

    MAKEVARS:

    PKG_CPPFLAGS= -I.
    PKG_LIBS= -L. -lexample_dll
    

    在调用 testwithdll2.dll 之前,还需要将 useDynlib 调用添加到命名空间中的 example_dll.dll。这也意味着 .C 调用需要指定 PACKAGE 参数,所以我不得不将 r 包装器更改为:

    timestwo.R

    #' @useDynLib example_dll
    #' @useDynLib testwithdll2
    #' @export
    timestwo <- function(n){
      .C("mydouble",n, PACKAGE = "testwithdll2")[[1]]
    }
    

    现在一切正常。

    【讨论】:

      猜你喜欢
      • 2010-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多