我正在尝试在 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/