Skip to content

Instantly share code, notes, and snippets.

@fdb
Last active May 30, 2021 13:27
Show Gist options
  • Save fdb/3d185e79956230c5f1ac9506a525ce5f to your computer and use it in GitHub Desktop.
Save fdb/3d185e79956230c5f1ac9506a525ce5f to your computer and use it in GitHub Desktop.
Calling Rust from C++
call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" x64
mkdir build
cl /nologo /Zi /MD /EHsc /I third_party\sdl\include shell/main.cpp /Febuild/win32_main2.exe /Fobuild/ /link /libpath:third_party\sdl\lib\win_x64 SDL2.lib SDL2main.lib /subsystem:console
cp third_party\sdl\lib\win_x64\SDL2.dll build
[package]
name = "vec"
version = "0.1.0"
authors = ["Frederik De Bleser <frederik@debleser.be>"]
[lib]
name = "vec"
crate-type = ["dylib"]
[dependencies]
#[repr(C)]
pub struct Vec2 {
x: f32,
y: f32,
// Adding a constructor here makes the code crash on Windows! :-O
// Vec2(f32 x_, f32 y_) : x(x_), y(y_) {}
}
#[repr(C)]
pub struct Vec4 {
x: f32,
y: f32,
z: f32,
w: f32,
// Adding a constructor here is no problem.
// Vec4(f32 x_, f32 y_, f32 z_, f32 w_) : x(x_), y(y_), z(z_), w(w_) {}
}
#[no_mangle]
pub extern "C" fn vec2_init() -> Vec2 {
Vec2 { x: 3.0, y: 5.0 }
}
#[no_mangle]
pub extern "C" fn vec4_init() -> Vec4 {
Vec4 { x: 3.0, y: 5.0, z: 7.0, w: 9.0 }
}
#include <SDL.h>
#include <stdint.h>
#include <stdio.h>
typedef int32_t i32;
typedef uint32_t u32;
typedef float f32;
struct Vec4 {
f32 x;
f32 y;
f32 z;
f32 w;
};
struct Vec2 {
f32 x;
f32 y;
};
#ifdef _WIN32
#define LIBRARY_FILENAME "target/debug/vec.dll"
#endif
typedef Vec4 (*vec4_init_t)();
typedef Vec2 (*vec2_init_t)();
int main(int, char**)
{
void *library_handle = SDL_LoadObject(LIBRARY_FILENAME);
if (library_handle == NULL) {
printf("COULD NOT LOAD LIB\n");
exit(-1);
}
auto vec4_init = (vec4_init_t) SDL_LoadFunction(library_handle, "vec4_init");
if (vec4_init == NULL) {
printf("COULD NOT FIND FN vec4_init\n");
exit(-1);
}
auto v4 = vec4_init();
printf("v4: %.2f %.2f %.2f %.2f\n", v4.x, v4.y, v4.z, v4.w);
auto vec2_init = (vec2_init_t) SDL_LoadFunction(library_handle, "vec2_init");
if (vec2_init == NULL) {
printf("COULD NOT FIND FN vec2_init\n");
exit(-1);
}
auto v2 = vec2_init();
printf("v2: %.2f %.2f \n", v2.x, v2.y);
return 0;
}
@IngwiePhoenix
Copy link

Is this still valid for 2019, and is there a package to allow me to automatically generate bindings like this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment