C
C#10mo ago
br4kejet

Best practices when using C++ DLL Project interop with C#?

I've implemented some of my project in C++ and I call that code from C#. My current way of loading the DLL is to call the LoadLibrary (and then use GetProcAddress + the Delegate helper method to invoke methods safely from C#). But I have to hard code the DLL's path, allowing it to either exist in the bin folder, or backing out of that folder to the solution folder and into x64, etc., to the built DLL file. How else can I load the DLL?
5 Replies
TheBoxyBear
TheBoxyBear10mo ago
Is the c++ project in the same solution as the c# project you're loading it from? In that case, MSBuild is very robust and there are many ways to configure your projects to automatically copy the dll from the c++ output to the c# output on build
br4kejet
br4kejetOP10mo ago
It is yeah
Omnissiah
Omnissiah10mo ago
you don't need to hardcode the path, you can load the dll from current/working directory
br4kejet
br4kejetOP10mo ago
That's becomes the bin folder of the app This is what I do now:
string binFilePath = Path.Combine(Path.GetFullPath("."), DLL_NAME);
if (!File.Exists(binFilePath)) {
#if DEBUG
binFilePath = "..\\..\\..\\..\\x64\\Debug\\" + DLL_NAME;
#else
binFilePath = "..\\..\\..\\..\\x64\\Release\\" + DLL_NAME;
#endif
}
string binFilePath = Path.Combine(Path.GetFullPath("."), DLL_NAME);
if (!File.Exists(binFilePath)) {
#if DEBUG
binFilePath = "..\\..\\..\\..\\x64\\Debug\\" + DLL_NAME;
#else
binFilePath = "..\\..\\..\\..\\x64\\Release\\" + DLL_NAME;
#endif
}
Omnissiah
Omnissiah10mo ago
you could get the executing path for example from System.Reflection.Assembly.GetExecutingAssembly().Location or if you don't have any specific necessity you could just try omitting the path
Want results from more Discord servers?
Add your server