The DLL compiled by rust cannot be loaded by loadlibrarya. The return value is 0

The rate type is set to cdylib or dylib

The content in is

pub extern "C" fn test() -> i32 {
return 123;

Then use the DLL compiled by loaded, and the result returns 0

How do you load and run the dll? What code do you use?

I call the DLL compiled by rust under Windows
Using Windows API, loadlibrary
Microsoft official document
Calling the compiled DLL with this API will return 0. If the function succeeds, the return value is a handle to the module

This is the DLL directory. One is compiled by rust and the other is compiled by C + +

This is C + + debugging code

This is the result of debugging

Don't Rust compiled DLLs support using the 'loadlibraryA' API call under Windows?

What API calls should be used under Windows?

Where are you calling the test function from rust?

How do you compile the Rust code?

Also what is your c++ code.

The code of C + + DLL is compiled directly with the example of visual studio

This is my Rust configuration

This is my Rust code

Then use cargo build --release

I could be an issue with 32 vs. 64 bit: imagining your C++ stuff is configured to use 32 bits, so that both the C++-compiled dll and the binary loading the DLL are 32-bit binaries, and Rust, on the other hand, may be emitting a 64-bit one.

Something that could help is to try and print the error message from LoadLibraryA. Could you apply the example showcased by Microsoft to see if we can get further information about the LoadLibraryA-yielding-NULL error?

Thank you. Yes, Rust does compile to x64 and will not load

Try to use cargo build --target i686-pc-windows-msvc to compile the DLL, then (feel free to add --release).

If you don't want to have to write that extra flag each time, you can also create a .cargo directory at the root of the crate, and a config file in it, with the following contents:

target = "i686-pc-windows-msvc"  # Compile for 32-bit windows

so that cargo build Just Works™ :slightly_smiling_face:

You will have to install the i686-pc-windows-msvc target for that. When using rustup that would be rustup target add i686-pc-windows-msvc.

1 Like

Indeed! You can also ensure any direct user of your repo will automagically download it through the rust-toolchain.toml file:

targets = [  # Automagically install these targets

Okay, thank you

I went to try it later, and I saw a similar configuration on the Internet

Add it under

rustflags = ["-C", "target-feature=+crt-static"]

Is it statically compiled

You shouldn't use use +crt-static for DLL's. That will statically link the c runtime into the DLL, which will then be different from the one used by the host executable. Having more than one c runtime inside a process is bound to give trouble.

OK, thank you for your clarification.