Reputation: 81
I have bought a printer device which was provided with a DLL enclosing the functionality and require to call the C++ functions inside that DLL from my C# code. However, I am always getting an error when I try to do so. Also using the same code provided with the application works fine. Following is some part of my code:
[DllImport("Msprintsdk.dll", EntryPoint = "SetInit", CharSet = CharSet.Ansi)]
public static extern unsafe int SetInit();
And calling the above function like:
var res = SetPrintport(new StringBuilder("USB001"),0);
if (res == 0)
{
Console.WriteLine("Printer Setup Successful.");
}
else
{
Console.WriteLine("Printer Setup Un-Successful.");
Console.ReadKey();
Environment.Exit(0);
}
Upvotes: 2
Views: 372
Reputation: 1
Do you have this declaration?
[DllImport("Msprintsdk.dll", EntryPoint = "SetPrintport", CharSet = CharSet.Ansi)]
public static extern unsafe int SetPrintport(StringBuilder strPort, int iBaudrate);
Upvotes: 0
Reputation: 1217
All possible issues you might face when working with C++ dll are listed as follows:
First of all do make sure you are placing the DLL in your \bin\Debug folder.
Next determine if the DLL is x86 or x64. In case of x86 DLL you need to check mark the Prefer 32-bit option in VS.
How it should be like (notice the Prefer 32-bit checked now):
Last but not the least you have to check the .NET framework your are using. If using .NET 3.5 your code should look something like:
[DllImport("Msprintsdk.dll", EntryPoint = "SetInit", CharSet = CharSet.Ansi)]
public static extern unsafe int SetInit();
var res = SetPrintport(new StringBuilder("USB001"),0);
if (res == 0)
{
Console.WriteLine("Printer Setup Successful.");
}
else
{
Console.WriteLine("Printer Setup Un-Successful.");
Console.ReadKey();
Environment.Exit(0);
}
If using .NET 4 or higher your code should look like:
[DllImport("Msprintsdk.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "SetInit", CharSet = CharSet.Ansi)]
public static extern unsafe int SetInit();
var res = SetPrintport(new StringBuilder("USB001"),0);
if (res == 0)
{
Console.WriteLine("Printer Setup Successful.");
}
else
{
Console.WriteLine("Printer Setup Un-Successful.");
Console.ReadKey();
Environment.Exit(0);
}
Notice the added CallingConvention = CallingConvention.Cdecl
.
These are the most common problems in my opinion anyone will come across when starting to work with C++ dlls.
Using your provided code to demonstrate the example as I am too lazy to write my own :). Hope this might help your case.
Upvotes: 1