How do I call a C function which returns many types of different function pointers?

ε祈祈猫儿з 提交于 2019-12-06 15:20:42

Here's a slightly smaller reproduction:

extern crate libc;

extern "C" {
    fn getProcAddress(procname: libc::c_int) -> extern "C" fn();
}

type CreateVertexArrays = extern "C" fn(n: libc::c_int, arrays: *mut libc::c_uint);

fn main() {
    let create_vertex_arrays: CreateVertexArrays = unsafe {
        getProcAddress(42)
    };

    let mut vao = 0;
    (create_vertex_arrays)(1, &mut vao);
}

One solution is The Big Hammer of "make this type into that type": mem::transmute:

fn main() {
    let create_vertex_arrays: CreateVertexArrays = unsafe {
        ::std::mem::transmute(getProcAddress(42))
    };

    let mut vao = 0;
    (create_vertex_arrays)(1, &mut vao);
}

But mem::transmute really is supposed to be used as the last resort. None of the other conversion techniques I'm aware of seem to apply here...


See also:

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!