rust导出C函数

cargo toml

[package]
name = "serialports"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
serialport ="*"
encoding = "*"
libc="*"

[lib]
crate-type=["cdylib"]

[profile.dev]
panic = "abort"

[profile.release]
panic = "abort"

rust code

use std::{thread,vec, string};
use libc;
use serialport;
use encoding::{DecoderTrap,all::GBK, Encoding};

//
#[no_mangle]
pub extern "C" fn callback(cfn :Option<extern "C" fn( c:* const libc::c_char)>){
    thread::spawn(move ||{
        loop{
            cfn.unwrap()(b"i love my father and mother\0".as_ptr() as *const libc::c_char);
            thread::sleep(std::time::Duration::from_secs(1));
        }      
    }); 
}

#[no_mangle]
pub extern "C"
fn portInit() {
    let ports = serialport::available_ports().expect("No Ports Found!");
    for p in ports {
        println!("{}", p.port_name);
    }
    //
    let mut com = serialport::new("COM2",115200)
    // .timeout(std::time::Duration::from_secs(20))
    .open()
    .unwrap();
    //
    com.write(b"hwoow").unwrap();
    //
    loop{
        let mut dat:[u8;256] = [0;256];
        let len = com.read(&mut dat[0..1]).unwrap();
        println!(" len is {}",len);
        //转换GBK
        //let s = GBK.decode(&dat[0..len], DecoderTrap::Strict).unwrap();

        println!("{:?}",  std::str::from_utf8(&dat[0..1]));
    }
}

c code

// testrust.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include <Windows.h>
//
typedef void(*Init)(void);
typedef void(*ByteCall)(void(*)(unsigned char *c));

//extern "C"
void bbb(unsigned char *b) {
	printf_s("%s\r\n", b);
}

int main()
{	
	
	HINSTANCE m = LoadLibrary(L"serialports.dll");
	//
	ByteCall c = (ByteCall)GetProcAddress(m, "callback");
	if (c) {
		c(bbb);
	}

	
	Init init = (Init)GetProcAddress(m, "portInit");
	
	if (init != nullptr) {
		init();
	}
	else {
		std::cout << "not found" << std::endl;;
	}


    std::cout << "Hello World!\n";
}
posted @ 2022-01-05 18:53  iwetuan  阅读(409)  评论(0编辑  收藏  举报