Use a C++ dll in c# - c#

I want to use a C++ dll IN a c# code
example (using the c++ dll):
class Program
{
[DllImport(#"netcoreapp3.1\savedecrypter.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern string decryptSave(string o);
static void Main(string[] args)
{
string ja = "dhsabdasji";
string show = decryptSave(ja);
Console.WriteLine(show);
Console.ReadLine();
}
}
**and this is the EXAMPLE C++ dll code(im just a newbie in c++ btw)**
extern "C"
{
__declspec(dllexport) string decryptSave(string path21)
{
return path21;
}
}
i got an error when trying to call it
"System.DllNotFoundException: 'Unable to load DLL 'netcoreapp3.1\savedecrypter.dll' or one of its dependencies: The specified module could not be found. (0x8007007E)'"
can anyone fix this for me? Would appreciate if somebody could do so.
edit : now i have enabled native code debbuging, it show this error :
Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

Is possible that your 'savedecrypter' DLL has a call to another DLL that is missing in your machine. Check if you have all the required drivers, this is a common mistake when you are working with third-party 'black-box' DLL's.

Related

Issue with std::wstring when calling from c# with DllImport

I was going to call an unmanaged function in a c++ library from c#, but it crashed. While troubleshooting I narrowed it down to std::wstring. A minimal example looks like this:
C++
#include <iostream>
extern "C" __declspec(dllexport) int __cdecl Start()
{
std::wstring test = std::wstring(L"Hello World");
return 2;
}
C#
using System.Runtime.InteropServices;
internal class Program
{
[DllImport("test.exe", CallingConvention=CallingConvention.Cdecl)]
public static extern int Start();
static void Main(string[] args)
{
var result = Start();
Console.WriteLine($"Result: {result}");
}
}
This gives me a Stack overflow. If I remove the line with std::wstring or I change it to std::string, there is no problem and I get back 2.
Can anyone explain to me what is going on here?
This is something I noticed:
[DllImport("test.exe", CallingConvention=CallingConvention.Cdecl)]
Exporting functions from an EXE instead of a DLL isn't standard. (I think it can be done, but I wouldn't recommend it.)
Build your C++ code as a DLL instead of an EXE. Statically link the DLL with the C++ runtime libraries to avoid missing dependency issues that could arise from not having the right DLLs in the loader search path.

To share an exported C++ DLL event, within an external C++ Win32 Application

Have a good day!
For portability reasons, i have created a C++ DLL with almost novice C++ knowledge just by searching thousands of pages, hundreds of compiling error corrections and couple of stackoverflow questions.
It is far beyond being stable but it is working most of the time :)
Just for curiosity and modularity reasons without importing the header and the cpp file to my application, i would like to ask your advice and help:
C++ Win32 Console Application
int main()
{
HMODULE lib = LoadLibrary(L"Serial.dll");
typedef void(*void_Connect)(UINT Port, UINT Baud);
void_Connect Connect = (void_Connect)GetProcAddress(lib, "Connect");
Connect(1, 9600);
}
I want to add an event into above C++ Win32 Console application, which will be triggered or hosted by the DLL
For example, a Received_Event(const char* data) or Connected_Event(BOOL status) with parameters.
Part from the DLL
typedef void(*fpCALLBACK) (const char* aParam);
static fpCALLBACK s_pCallback = NULL;
extern "C"
{
#define DLL __declspec(dllexport)
DLL void ReceivedEventRegister(fpCALLBACK p_pCallback)
{
s_pCallback = p_pCallback;
}
DLL void evntReceived(const char *receivedData);
}
DLL void evntReceived(const char *received)
{
s_pCallback(received);
}
I want to achive something similar to this C# version, with Standard C++
private static ManagedCallbackDelegate MessageCallbackDelegate;
public delegate void ManagedCallbackDelegate(string aParam);
[DllImport("Serial.dll", EntryPoint = "ReceivedEventRegister", CallingConvention = CallingConvention.Cdecl)]
private static extern void ReceivedEventRegister(ManagedCallbackDelegate callback);
static private void serialRecieved(string data)
{
Console.WriteLine(data);
}
static void Main(string[] args)
{
MessageCallbackDelegate = new ManagedCallbackDelegate(serialRecieved);
ReceivedEventRegister(MessageCallbackDelegate);
}
With C# code above, any data received by the DLL, the serialRecieved function is called in realtime. I want to achive this with Standard C++
I want to be informed or be aware of with the DLL process in realtime, in my Win32 C++ Console Application. ( Without blocking the Win32 Console application )
No MFC. if it is possible, no Component Object Model (It is possible with C# without need to convert the DLL into a COM). if it is possible, I want to do it with Standard C++.
I am compiling things with Visual Studio 2017 Community
Please go easy with me. It is a hobby for me and i just do it in my spare time.
Questions
Can you reference me some code examples written for this purpose, you are aware of?
Is there any specific name for this kind of communication that i can Google?
Is there any approach, you can suggest?
Thank you!
Once again, thanks to #dxiv's comment; helped me a lot, to sort things out! Even, when someone tells you that it should work, you resolve 90% of the problem.
At the DLL side
DLL void evntReceived(const char *received)
{
s_pCallback(received);
}
The DLL is calling the above function all the time as soon as it receives any data. To get that data realtime in your Win32 C++ Application, you need to import the DLL function which is calling the above callback function. Which is this
DLL void ReceivedEventRegister(fpCALLBACK p_pCallback)
part of the DLL.
As the DLL function's parameter type name fpCALLBACK suggests, our function parameter has to be as it is defind in the DLL:
typedef void(*fpCALLBACK) (const char* aParam);
At the Application side
//Callback Function: A function that is passed to another function as an argument
void Event_Received(const char *recvd)
{
std::cout << recvd << std::endl;
}
int main()
{
HMODULE lib = LoadLibrary(L"Serial.dll");
typedef void(*void_Connect)(UINT Port, UINT Baud);
void_Connect Connect = (void_Connect)GetProcAddress(lib, "Connect");
// Type definition of the function pointer.
// In our case: a Void type, which takes in a
// void type function pointer with a parameter (const char *aParam)
// dllCALLBACK is just a type name; you can name it whatever you want.
typedef void(*dllCALLBACK) (void(*fpCALLBACK) (const char* aParam));
// Now we will import the function from our DLL which takes
// the same parameters as we defined above, to call
// our callback function
dllCALLBACK ReceivedEventRegister = (dllCALLBACK)GetProcAddress(lib, "ReceivedEventRegister");
// Call the callback function with the imported function above.
// And that is all there is to it. As soon as any data received
// by our DLL - our Event_Received callback function
// fires in our C++ Win32 Console Application
ReceivedEventRegister(Event_Received);
Connect(1, 9600);
}
If you are a novice like me this video may help you to understand about Callback functions.
Thank you #dxiv again, taking time to read and answer my question!

Problems using methods from DLL - EntryPoints

I need to use a DLL created in C in a C # application. I have followed several ways seen on the internet and I can not use the methods that are supposed to be in the DLL.
When looking for the entrypoints I get 4, which are the following.
DllCanUnloadNow
llGetClassObject
DllRegisterServer
DllUnregisterServer
I'm trying with the following code:
[DllImport("DLL.dll", EntryPoint ="DllCanUnloadNow" ,CharSet = CharSet.Auto)]
public static extern int Open();
static void Main(string[] args)
{
Console.WriteLine(Open());
Console.ReadLine();
}
It doesn't matter what function I use, it returns always 0.
If I use a function called for example, asdf() I got 0.
Does anyone know how to use the DLL correctly? I think it's made as COM and I have a .lib file.
Thanks in advance.

embedding c++ native dll in set up

I want to embed c++ native dll in set up file created with install shield limited edition.
Hint :- My application created by using c# and c++ native dll.
Here is my example :-
My c++ dll_code
extern "c" __declspec(dllexport) int function_c ()
{
int a=10;
return a;
}
My .net code
public partial class Form1 : Form
{
[DllImport(#"C:\Users\bajwa\Documents\Visual Studio 2012\Projects\c++dll\c++_dll.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
static extern int function_c();
void csharp_function()
{
int result= function_c(); // calling c++ native function
MessageBox.Show(result);
}
private void button1_Click(object sender, EventArgs e)
{
csharp_function(); // calling c# function.
}
}
When I installed this setup on my computer it runs perfectly. Because C++ native dll is placed on my computer at "C:\Users\bajwa\Documents\Visual Studio 2012\Projects\c++dll\c++_dll.dll".
But when I delete the c++ native dll from that location then it shows the error.
dll not fount at this location
Please help and solve my problem.
I think you will just need to use a relative path for the imported DLL. The easiest thing to do would be to copy the DLL to a known folder relative to the executable (maybe even the same folder) and then use that path. So if they share a folder, your code can become this:
[DllImport("c++_dll.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
static extern int function_c();
Then just modify the installer to place the dll in the correct location. To test, just change your code and move the dll over, but it should work.

"Unable to find an entry point named" in c# using a C dll

I am trying a simple program to access a C function through a dll into a C# program,
class DllImportTest
{
[DllImport("TestApp.dll", EntryPoint = "main1")]
public static extern void main1();
}
class Program
{
static void Main(string[] args)
{
DllImportTest.main1() ;
}
I have seen through the code and the name of the function is the exactly right. I have also tried using Extern "C" but, it throws me an error as its .C file.
I have placed the .Dll in the C# executable folder.
Is there something that I am doing wrong here?
Found it!
I had to use Extern "C" coupled with __declspec(dllexport) . I had never used both together, Thanks guys

Categories