`
bcyy
  • 浏览: 1823564 次
文章分类
社区版块
存档分类
最新评论

Matlab调用动态链接库

 
阅读更多

版权所有,转载请注明出处:http://guangboo.org/2013/05/02/matlab-dll-file

Matlab的优势就是矩阵计算,大量的算法库等,对于非矩阵计算来说可能就没有多高的性能和优势。Matlab支持使用C语言和Fortan编写扩展,这样就可以弥补Matlab不擅长的部分。有些时候我们需要在Matlab中调用已有的dll,避免写C扩展。

比如需要在matlab中获取机器码,而这个机器码的获取方法是现成的,只是这个方法是使用C编写的,并已经编译成libhelper.dll文件里。那么我们就可以这些编译一个get_mac_id的函数,来调用该dll中的函数get_machine_code的方法。

需要有libhelper.h文件,该头文件要包含get_machine_code函数的声明,如:

int __stdcall get_machine_code(char *buf);

libhelper.h头文件是必须的,并且文件名也要和dll文件名一致。然后可以编写m文件get_id.m,如下:

function code = get_mac_id()
%GETID Summary of this function goes here
%   Detailed explanation goes here
try
    [notfound,warnings] = loadlibrary('libhelper.dll');
    arg = '';
    %arg = libpointer('stringPtr',buf);
    [a, buf2] = calllib('libhelper', 'get_machine_code', arg);
    unloadlibrary('libhelper');
catch
    code = '';
    return;
end

buf = unicode2native(buf2, '');

mac_buffer = repmat('0', 1, 64);
len = length(buf2);

for i=1:len
    c =  dec2hex(uint8(buf(i)));
    if length(c) == 1
        mac_buffer(i*2-1:i*2) = ['0' c];
    else
        mac_buffer(i*2-1:i*2) = c;
    end
end

if length(mac_buffer) > 32
    code = mac_buffer(1:32);
else
    code = mac_buffer;
end
end

调用方法:

>> 
>> get_mac_id()

ans =

3F5E5DB9083770DA154D15A55431229C

>> 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics