c - 使用与用 nasm 组装的对象链接的 matlab 混合 C 代码时出错

标签 c matlab assembly nasm mex

我正在尝试在 Matlab 中混合 C 代码,该代码与我使用 nasm 组装的对象链接。当我尝试混合代码时,我收到来自 Matlab 的错误。这是我用来混合代码的命令:

    mex main.c hello.o

这是 C 代码:

    #include <stdio.h>
    #include <stdlib.h>
    #include "mex.h"

    extern char * helloWorld();

    void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])  {
        char * sentence = helloWorld();
        printf("%s\n", sentence);
    }

汇编代码如下:

    global helloWorld

    section .data
        greeting: db "Hello, World", 0
    section .text
    helloWorld:
        mov eax, greeting
        ret

我用来汇编代码的命令是:

    nasm -felf64 -gdwarf2 -o hello.o hello.asm

这是我在尝试混合 C 代码时收到的错误:

    /usr/bin/ld: hello.o: relocation R_X86_64_32 against `.data' can not be used
    when making a shared object; recompile with -fPIC
    hello.o: could not read symbols: Bad value
    collect2: ld returned 1 exit status

nasm 没有 -fPIcflags。我尝试使用 get_GOT 宏以及默认 rel,但我仍然遇到相同的错误。所有帮助将不胜感激。 谢谢你

最佳答案

我在使用 VS2010 作为编译器的 Windows 机器(WinXP 32 位)上。这是我所做的:

  • Windows 下载 NASM 汇编程序

  • 在汇编代码中为导出的符号名称添加下划线:

    global _helloWorld
    
    section .data
        greeting: db "Hello, World", 0
    section .text
    _helloWorld:
        mov eax, greeting
        ret
    
  • 编译汇编代码如下:nasm -f win32 -o hello.obj hello.asm

  • 在 MATLAB 中,编译链接到生成的目标文件的 MEX 文件:

    >> mex main_mex.c hello.obj
    

    正如我所说,mex 之前配置为使用 Visual Studio 2010 进行编译。

    #include <stdio.h>
    #include <stdlib.h>
    #include "mex.h"
    
    extern char* helloWorld();
    
    void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
    {
        char *sentence = helloWorld();
        mexPrintf("%s\n", sentence);
    }
    
  • 运行 MEX 函数:

    >> main_mex
    Hello, World
    

编辑:

在 64 位 Windows 上,我做了以下更改:

bits 64        ; specify 64-bit target processor mode
default rel    ; RIP-relative adresses

section .text
global helloWorld      ; export function symbol (not mangled with an initial _)
helloWorld:
    mov rax, greeting  ; return string
    ret

section .data
    greeting: db "Hello, World", 0

然后:

>> !nasm -f win64 -o hello.obj hello.asm
>> mex -largeArrayDims hello_mex.c hello.obj
>> hello_mex
Hello, World

关于c - 使用与用 nasm 组装的对象链接的 matlab 混合 C 代码时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18367089/

相关文章:

c - 我如何将结构指针数组中的结构直接复制到c中的另一个结构

MATLAB:如何在矩阵中设置颜色

assembly - 使用 objdump 时确定寄存器值

assembly - 使用 gdb 从内存位置读取?

c - 错误在 './a.out' : free(): invalid*** Error in `./allum1' : free(): invalid next size (fast): 0x00000000023e13f0 ***

c - C 中的高级预处理器标记化

matlab - 如何在 Matlab 中将字符串转换为函数句柄?

assembly - 为什么 i++ 在单核机器上不是线程安全的?

c++ - 将 Firefox 和 Chrome cookie 导入 libcurl

c++ - 如何用OpenCV模拟Matlab的medfilt2?