简体   繁体   中英

Porting DLL import from c# to c++

This is how I use/import the DLL using c#. How do I do it on c++ project?

[DllImport(@".\x64\something.dll", EntryPoint = "somthng", CharSet = CharSet.Unicode)]
static extern int somthng(string input);

Provided that you do not have the development header and lib files available for the DLL and you need to dynamically load the DLL into your C++ project, then you can do the following.

Define a function pointer (equivalent to your extern declaration):

typedef int FnSomeFunction(const char* input);

Load the library (I'm using LoadLibraryA here to load an ansi-named DLL, this depends on your C++ project). The DLL must be in the search path, ie in the same path as the executable):

HMODULE hModule = LoadLibraryA("something.dll");

Check that the module is successfully loaded:

if (hModule == nullptr)
    throw std::runtime_error("Lib not loaded");

Get the function entry point from the library:

FnSomething* fnSomething = (FnSomeFunction*)GetProcAddress(hModule, "somthng");

Call the function:

(*fnSomething)("some text");

Free the library when no longer needed:

FreeLibrary(hModule);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM