2

我买了一个打印机设备,它提供了一个包含该功能的 DLL,并且需要从我的 C# 代码调用该 DLL 中的 C++ 函数。但是,当我尝试这样做时,我总是会遇到错误。使用应用程序提供的相同代码也可以正常工作。以下是我的代码的一部分:

[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);
}
4

1 回答 1

1

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.

于 2019-04-09T09:15:14.240 回答