导入的C函数在C#中起作用,但在VB6中不起作用

问题描述 投票:3回答:2

我正在研究问题几天,似乎找不到答案。我有一个用C编写的第三方dll,必须在VB6应用程序中使用。

dll中的函数看起来像这样:

someFunction(WContext* context, const unsigned char* seed, int seedLength, const unsigned char* name, int nameLength, 
             const unsigned char* pin, int pinLength, const char* description)

我有一个用C#编写的示例。我尝试了一下,效果很好。这就是C#中的样子

[DllImport("Filename.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern int someFunction(IntPtr context, byte[] seed, int seedLength, byte[] name, int nameLength, 
                                       byte[] pin, int pinLength, string description)

稍后将在这样的示例中使用:

byte[] seed = Encoding.ASCII.GetBytes("seed")
byte[] name = Encoding.ASCII.GetBytes("name")
byte[] pin = Encoding.ASCII.GetBytes("1234")
string description = "description"

int result = someFunction(context, seed, seed.length, name, name.Length, pin, pin.Length, description)

现在这在C#中很好用。结果为0,这表示该操作成功。我想在VB6中进行这项工作。我尝试了dll的某些其他功能,它们按应有的方式工作。这让我头疼。这就是我尝试过的其他功能:

首先,我将该函数导入到我的代码中,以便以后使用。我以相同的方式使用了其他一些功能,效果很好。

Private Declare Function someFunction Lib "C:\DllPath\Filename.dll" (ByVal context As Long, ByRef seed as Byte, _
                                                                     ByVal seedLength As Integer, ByRef name As Byte, _
                                                                     ByVal nameLength As Integer, ByRef pin As Byte, _
                                                                     ByVal pinLength As Integer, ByVal description As String) As Integer

下一步是我调用该函数。我这样做是这样的:(我确实早先从另一个函数获取了上下文,所以它已经有了一个值。其他函数对该变量也能正常工作)

Dim seed() As Byte
Dim seedLength As Integer
Dim name() As Byte
Dim nameLength As Integer
Dim pin() As Byte
Dim pin As Integer
Dim description As String
Dim result as Integer

seed = StrConv("seed", vbFromUnicode)
seedLength = UBound(seed) + 1
name = StrConv("name", vbFromUnicode)
nameLength = UBound(name) + 1
pin = StrConv("1234", vbFromUnicode)
pinLength = UBound(pin) + 1
description = "description"

result = someFunction(context, seed(0), seedLength, name(0), nameLength, pin(0), pinLength, description)

结果的值为1。根据文档,我得到的是无效参数。现在我做了很多研究。读到在VB6中我必须像在代码中一样给字节数组的第一个元素。首先对整个数组进行了尝试,得到了相同的结果。我认为这与数组有关,因为它是我接管有这些代码的代码中的第一个函数。我也不是VB6的本地人,但我必须这样做。也许你们当中有些人知道为什么这行不通。我可能只是一个小错误。

我正在研究问题几天,似乎找不到答案。我有一个用C编写的第三方dll,我必须在VB6应用程序中使用它。 dll中的函数看起来...

c# c dll vb6
2个回答
0
投票

当调用已声明的API时,VB6会自动将字符串转换为ANSI字节数组,因此您可以将种子,名称和引脚声明为ByVal字符串。


-1
投票

您可以尝试在VB中更改函数声明,将种子,名称和引脚ByRef设置为Byte(),

© www.soinside.com 2019 - 2024. All rights reserved.