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

>> 
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值