Ali Abdullah
Ali Abdullah

Reputation: 81

Trouble calling DLL function

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

Answers (2)

Marcos Rincon
Marcos Rincon

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

Tayyab
Tayyab

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.

What it will look like: enter image description here

How it should be like (notice the Prefer 32-bit checked now):

enter image description here

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

Related Questions