1

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);
TerribleDog
  • 1,237
  • 1
  • 8
  • 31

1 Answers1

0

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, i.e. 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);
J.R.
  • 1,880
  • 8
  • 16
  • Alternatively, just build your C++ project against the appropriate header (.h) and import library (.lib) so that you can just call the function directly. If you can link directly against the import library, it will be much more convenient if there are a lot of functions to import. – jazzdelightsme Mar 29 '19 at 03:44
  • True; my assumption was that these were not available. I'll update the answer to reflect this. – J.R. Mar 29 '19 at 03:53