这已被问过一百万次,但我仍然无法让它工作。所以我问: 我有一个 DLL 导入(非托管 C/C++ 代码),我想从 C# 调用但无法开始工作。我正在从 VB.net 移植,那里的代码(有效)如下:
Module Module1
Public Declare Function autodetect_SearchAxis Lib "autodetect.dll" (ByVal onusb As Boolean, ByVal searchsubadress As Byte, ByRef portname As String, ByRef devicelocation As String) As Integer
Public AxisCom As String
Public AxisAdress As Byte = 1
Public Dummy As String
Public rc As Integer
Sub Main()
Dummy = Space(1024)
AXISCom = Space(1024)
rc = autodetect_SearchAxis(False, AxisAdress, Dummy, AxisCom)
Debug.WriteLine("rc: " + rc.ToString())
Debug.WriteLine("AxisCom: " + AxisCom.ToString())
End Sub
End Module
我手头没有我的 C# 代码尝试 ATM,但我已经使用 SttingBuilder
类尝试了各种版本。如果有人可以帮助我将此代码移植到 C#,我将不胜感激。提前致谢!
编辑:
我现在有了 DLL 函数的签名:
int _stdcall autodetect_SearchAxis(bool onusb, BYTE searchsubadress, char* &portname, char* &devicelocation)
David Heffernan 建议的解决方案部分有效。它正在工作(我没有错误消息),但返回的字符串是垃圾。本质上这是我已经在工作的(具有相同的垃圾输出)。我不确定这是否与字符编码有关(我没有收到任何错误消息)。希望签名对您有所帮助。
最佳答案
基本上应该是:
using System.Diagnostics;
using System.Runtime.InteropServices;
public static class Module1
{
[DllImport("autodetect.dll")]
public static extern int autodetect_SearchAxis(bool onusb, byte searchsubadress, ref string portname, ref string devicelocation);
public static string AxisCom;
public static byte AxisAddress = 1;
public static string Dummy;
public static int rc;
public static void Main()
{
Dummy = new string(' ', 1024);
AxisCom = new string(' ', 1024);
rc = autodetect_SearchAxis(false, AxisAddress, ref Dummy, ref AxisCom);
Debug.WriteLine("rc: " + rc.ToString());
Debug.WriteLine("AxisCom: " + AxisCom.ToString());
}
}
关于c# - 将此 DLL 包含从 VB.net 翻译成 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32954370/