VB.net Passing a structure to unmanaged dll

空扰寡人 提交于 2019-12-09 19:25:52

问题


I'm migrating some VB6 code to VB.net, the code contains a structure that contains 1d arrays, 2d arrays, and few other variables.

The general outline of the Vb.net structure is as under

Public Structure Test

    Dim a As Single
    Dim b As Single
    Dim c As Single
    <VBFixedArray(2)> Dim arr1() As Single
    <VBFixedArray(2, 2)> Dim mdarr1(,) As Single
    <VBFixedArray(4)> Dim arr2() As Byte
    <VBFixedArray(4)> Dim arr3() As Short
    <VBFixedArray(3, 2)> Dim mdarr2(,) As Integer

    Dim d As Integer
    Dim e As Decimal

End Structure

The call to the dll is declared as under

Public Declare Sub getState Lib "val.dll" (ByRef state As Test)

Elsewhere on this site I realized that we have to "marshal" the structure to allow it to be compatible with the unmanaged code that is about to accept it.

However I still receiving runtime errors when running the code, I don't have any clue of how to use the System.Runtime.InteropServices.Marshal class.

What would be the correct way to pass this structure to the dll?

EDIT:

The original VB6 data type is

Public Type Test

    a As Single
    b As Single
    c As Single
    arr1(0 To 2) As Single
    mdarr1(0 To 2, 0 To 2) As Single
    arr2(0 To 4) As Byte
    arr3(0 To 4) As Integer
    mdarr2(0 To 3, 0 To 2) As Long

    d As Long
    e As Currency

End Type

回答1:


Do you have the source code for getState in the val.dll? If it's written in C or C++, and you have the source code or even just the headers, you could use the P/Invoke Assistant to automatically generate your VB.Net code.

Alternatively... (and please do post the original VB6 structure!)

  • You might need to allocate the arrays before calling getState, e.g. state.arr1 = {0.0, 0.0} etc.
  • The Decimal variable e could cause you a problem. In VB6 this was probably a Currency variable, and Decimal is not an exact equivalent as far as I can remember. There will be a way to tell VB.Net to marshal it like a Currency. Perhaps adding an attribute like this...

Sample code:

 Imports System.Runtime  
 Public Structure Test  
   ''blah blah

   <InteropServices.MarshalAs(InteropServices.UnmanagedType.Currency)> _  
   Dim e As Decimal  

   ''blah blah


来源:https://stackoverflow.com/questions/5072831/vb-net-passing-a-structure-to-unmanaged-dll

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!