473,757 Members | 8,085 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Passing Pointers to Structs

Hi, I'm working on a VB project which involves using C
library functions which take struct pointers as args, and
I keep running into this error when trying to pass either
an IntPtr or a Structure ByRef to the functions.

An unhandled exception of
type 'System.Runtime .InteropService s.MarshalDirect iveExcept
ion' occurred in ConsoleApplicat ion1.exe

Additional information: PInvoke restriction: can not
return variants.

Can someone please give me a general idea of what "cannot
return variants" means? The function that I've imported
takes a struct pointer and returns void.
Nov 20 '05 #1
8 1790
On 2003-11-21, Bryan G <an*******@disc ussions.microso ft.com> wrote:
Hi, I'm working on a VB project which involves using C
library functions which take struct pointers as args, and
I keep running into this error when trying to pass either
an IntPtr or a Structure ByRef to the functions.

An unhandled exception of
type 'System.Runtime .InteropService s.MarshalDirect iveExcept
ion' occurred in ConsoleApplicat ion1.exe

Additional information: PInvoke restriction: can not
return variants.

Can someone please give me a general idea of what "cannot
return variants" means? The function that I've imported
takes a struct pointer and returns void.


Bryan,

It is really hard to answer a question like this without seeing both the
C definitions of the structure and function and seeing your VB
declarations. If you could post that information, I or someone else, I
am sure, would be happy to help you.

--
Tom Shelton
[MVP - Visual Basic]
Nov 20 '05 #2
-----Original Message-----
On 2003-11-21, Bryan G <an*******@disc ussions.microso ft.com> wrote:
Hi, I'm working on a VB project which involves using C
library functions which take struct pointers as args, and I keep running into this error when trying to pass either an IntPtr or a Structure ByRef to the functions.

An unhandled exception of
type 'System.Runtime .InteropService s.MarshalDirect iveExcep
t ion' occurred in ConsoleApplicat ion1.exe

Additional information: PInvoke restriction: can not
return variants.

Can someone please give me a general idea of what "cannot return variants" means? The function that I've imported takes a struct pointer and returns void.


Bryan,

It is really hard to answer a question like this without

seeing both theC definitions of the structure and function and seeing your VBdeclarations . If you could post that information, I or someone else, Iam sure, would be happy to help you.

--
Tom Shelton
[MVP - Visual Basic]
.

Hi Tom,

I am working with Bryan on this. Here's an example:

This a a testing struct we put in the C library:

typedef struct GetLongRTS *GetLongRT;
struct GetLongRTS{
CHAR sval;
LONG lval;
};

These are the access functions for it.

DBACCESSDLL_API GetLongRT __cdecl GetLongVal(){
struct GetLongRTS GL;
GetLongRT temp = malloc(sizeof(s truct
GetLongRTS));
return temp;
}

DBACCESSDLL_API void __cdecl SetLongVal(GetL ongRT temp){
temp->sval = 'b';
}

These are the VB acess functions and the struct
declaration:

Public Structure GetLongRTS
Public sval As Char
Public lval As Integer
End Structure

<DllImport("DBA ccess.dll", SetLastError:=T rue)> _
Public Shared Function GetLongVal() As IntPtr
End Function

<DllImport("DBA ccess.dll", SetLastError:=T rue)> _
Public Shared Function SetLongVal(ByRe f temp As
GetLongRTS)
End Function

And finally the code that when executed gives the errors
Bryan described:

Imports System.Text
Imports System.Runtime. InteropServices
Imports System.Reflecti on

Module Module1
Sub Main()
Dim ptr As IntPtr = DBAccessFuncDec l.GetLongVal()
Dim obj As DBAccessFuncDec l.GetLongRTS = _
CType(Marshal.P trToStructure(p tr, GetType
(DBAccessFuncDe cl.GetLongRTS)) ,
DBAccessFuncDec l.GetLongRTS)
'Dim obj As DBAccessFuncDec l.GetLongRTS
'Marshal.Struct ureToPtr(obj, ptr, True)
DBAccessFuncDec l.SetLongVal(ob j)

Console.WriteLi ne(obj.lval)

End Sub
End Module

Sorry about the formatting. Let me know if you need more
info.

Separate but related question:

Are these two structures equivalent?

C code:

struct cstruct {

long l;

char c;

char *str;

int[30] ivals;

byte b;

lpvoid tmp;

char[20][30] string_array;

}

VB code:

Public Structure vbstruct

Public l As Integer

Public c As Char

Public str As StringBuilder

Public ivals As ArrayList

Public b As Byte

Public tmp As IntPtr

Public string_array As ArrayList

End Structure

Thanks,

Denis
Nov 20 '05 #3
On 2003-11-21, Denis C <an*******@disc ussions.microso ft.com> wrote:
-----Original Message-----
On 2003-11-21, Bryan G<an*******@dis cussions.micros oft.com> wrote:


<snip>

Ok, something to work with :). And I see a couple of things already...
Hi Tom,

I am working with Bryan on this. Here's an example:

This a a testing struct we put in the C library:

typedef struct GetLongRTS *GetLongRT;
struct GetLongRTS{
CHAR sval;
LONG lval;
};

These are the access functions for it.

DBACCESSDLL_API GetLongRT __cdecl GetLongVal(){
struct GetLongRTS GL;
GetLongRT temp = malloc(sizeof(s truct
GetLongRTS));
return temp;
}

DBACCESSDLL_API void __cdecl SetLongVal(GetL ongRT temp){
temp->sval = 'b';
}

These are the VB acess functions and the struct
declaration:

Public Structure GetLongRTS
Public sval As Char
Public lval As Integer
End Structure
I'm assuming that CHAR is a typedef for char, and there for is an 8-bit
char... If that is so, then you'll want to change this to:

<StructLayout(L ayoutKind.Seque ntial, CharSet:=CharSe t.Ansi)>
Public Structure GetLongRTS
Public sval As Char
Public lval As Integer
End

<DllImport("DBA ccess.dll", SetLastError:=T rue)> _
Public Shared Function GetLongVal() As IntPtr
End Function

<DllImport("DBA ccess.dll", SetLastError:=T rue)> _
Public Shared Function SetLongVal(ByRe f temp As
GetLongRTS)
End Function

These declares are where your real problem lies though... You have the
C declarations using __cdecl. The default marshalling is for __stdcall.
So, you either need to change the C functions or add the
CallingConventi on attribute to your VB.NET declares:

<DllImport("DBA ccess.dll", CallingConventi on:=CallingConv ention.Cdecl, SetLastError:=T rue)> _
Public Shared Function GetLongVal() As IntPtr
End Function

<DllImport("DBA ccess.dll", CallingConventi on:=CallingConv ention.Cdecl, SetLastError:=T rue)> _
Public Shared Function SetLongVal(ByRe f temp As GetLongRTS)
End Function
And finally the code that when executed gives the errors
Bryan described:

Imports System.Text
Imports System.Runtime. InteropServices
Imports System.Reflecti on

Module Module1
Sub Main()
Dim ptr As IntPtr = DBAccessFuncDec l.GetLongVal()
Dim obj As DBAccessFuncDec l.GetLongRTS = _
CType(Marshal.P trToStructure(p tr, GetType
(DBAccessFuncDe cl.GetLongRTS)) ,
DBAccessFuncDec l.GetLongRTS)
'Dim obj As DBAccessFuncDec l.GetLongRTS
'Marshal.Struct ureToPtr(obj, ptr, True)
DBAccessFuncDec l.SetLongVal(ob j)

Console.WriteLi ne(obj.lval)

End Sub
End Module

Sorry about the formatting. Let me know if you need more
info.

Separate but related question:

Are these two structures equivalent?

C code:

struct cstruct {

long l;

char c;

char *str;

int[30] ivals;

byte b;

lpvoid tmp;

char[20][30] string_array;

}

VB code:

Public Structure vbstruct

Public l As Integer

Public c As Char

Public str As StringBuilder

Public ivals As ArrayList

Public b As Byte

Public tmp As IntPtr

Public string_array As ArrayList

End Structure


Nope... This one is actually a little harder - because of the 2D
array. I it would most likely have to be done something like:

<StructLayout(L ayoutKind.Seque ntial, CharSet=CharSet .Ansi)> _
Public Structure vbstruct
Public l As Integer

Public c As Char

' you can't marshal stringbuilder inside of
' a structure, have to use string
Public str As String

<MarshalAs(Unma nagedType.ByVal Array, SizeConst:=30)> _
Public ivals() As Integer

Public b As Byte

Public tmp As IntPtr

<MarshalAs(Unma nagedType.ByVal Array, SizeConst:=600) > _
Public string_array() As Char
End Sub

Basically, you would probably have to flatten the char array into a
single demension, and then chunk it up after the call manually. At
least, I haven't found a way to pass fixed size multidemensiona l arrays.
You could ask over on the interop group though, incase I missed it :)

--
Tom Shelton
[MVP - Visual Basic]
Nov 20 '05 #4
<snip>

<StructLayout(L ayoutKind.Seque ntial, CharSet=CharSet .Ansi)
_
Public Structure vbstruct
Public l As Integer

Public c As Char

' you can't marshal stringbuilder inside of
' a structure, have to use string
Public str As String

<MarshalAs(Unma nagedType.ByVal Array, SizeConst:=30)> _ Public ivals() As Integer

Public b As Byte

Public tmp As IntPtr

<MarshalAs(Unma nagedType.ByVal Array, SizeConst:=600) > _ Public string_array() As Char
End Sub

Basically, you would probably have to flatten the char array into asingle demension, and then chunk it up after the call manually. Atleast, I haven't found a way to pass fixed size multidemensiona l arrays.You could ask over on the interop group though, incase I missed it :)
--
Tom Shelton
[MVP - Visual Basic]
.


Thanks again, we're both new to VB and are unsure as to
what you can do with it. I should have mentioned that
this application will eventually be for Windows CE 4.2.
On there there is no MarshalAs and I believe the String
handling is different.

CHAR is a standard C char.

Is the passing of the structure in SetLongVal correct?

Thanks again,

Denis
Nov 20 '05 #5
On 2003-11-21, Tom Shelton <to*@lsnfcdm.co m> wrote:
On 2003-11-21, Denis C <an*******@disc ussions.microso ft.com> wrote:
-----Original Message-----
On 2003-11-21, Bryan G

<an*******@di scussions.micro soft.com> wrote:


<snip>

Ok, something to work with :). And I see a couple of things already...


And now that I know this is for the compact framework, things are a
little different. I'm not a great expert there, but I believe that the
calling convention is Cdecl there... So, you can disregard that.
Actually looking closer, I thinkg the problem is with your declaration
of SetLongVal....
DBACCESSDLL_API void __cdecl SetLongVal(GetL ongRT temp){
temp->sval = 'b';
}

<DllImport("DBA ccess.dll", SetLastError:=T rue)> _
Public Shared Sub SetLongVal(ByRe f temp As GetLongRTS)
End Sub

It returns void... So that is a Sub in VB - not a function, which
probably explains the variant error. If you still have troubles, then
you may want to post your questions to the framework interop group. I
know a bit about using marshalling in the framework, but I don't have
any experience at all with the compact framework. You might have better
luck over there if this doesn't solve it.

--
Tom Shelton
[MVP - Visual Basic]
Nov 20 '05 #6
-----Original Message-----
On 2003-11-21, Tom Shelton <to*@lsnfcdm.co m> wrote:
On 2003-11-21, Denis C <an*******@disc ussions.microso ft.com> wrote:

-----Original Message-----
On 2003-11-21, Bryan G
<an*******@d iscussions.micr osoft.com> wrote:
<snip>

Ok, something to work with :). And I see a couple of things already...


And now that I know this is for the compact framework,

things are alittle different. I'm not a great expert there, but I believe that thecalling convention is Cdecl there... So, you can disregard that.Actually looking closer, I thinkg the problem is with your declarationof SetLongVal....
DBACCESSDLL_API void __cdecl SetLongVal(GetL ongRT temp){ temp->sval = 'b';
}


<DllImport("DB Access.dll", SetLastError:=T rue)> _
Public Shared Sub SetLongVal(ByRe f temp As GetLongRTS)
End Sub

It returns void... So that is a Sub in VB - not a

function, whichprobably explains the variant error. If you still have troubles, thenyou may want to post your questions to the framework interop group. Iknow a bit about using marshalling in the framework, but I don't haveany experience at all with the compact framework. You might have betterluck over there if this doesn't solve it.

--
Tom Shelton
[MVP - Visual Basic]
.


Thanks again for all the help. I guess the main thing we
were looking for was passing pointers into a C library
from VB. We read that Structures in VB could only be
passed by value and were unsure how to proceed. Your
help is very much appreciated.

Denis
Nov 20 '05 #7
On 2003-11-22, Denis C <an*******@disc ussions.microso ft.com> wrote:
-----Original Message-----
On 2003-11-21, Tom Shelton <to*@lsnfcdm.co m> wrote:
On 2003-11-21, Denis C<an*******@dis cussions.micros oft.com> wrote:
>-----Original Message-----
>On 2003-11-21, Bryan G
<an*******@ discussions.mic rosoft.com> wrote:

<snip>

Ok, something to work with :). And I see a couple of things already...


And now that I know this is for the compact framework,

things are a
little different. I'm not a great expert there, but I

believe that the
calling convention is Cdecl there... So, you can

disregard that.
Actually looking closer, I thinkg the problem is with

your declaration
of SetLongVal....
DBACCESSDLL_API void __cdecl SetLongVal(GetL ongRT temp){ temp->sval = 'b';
}

<DllImport("D BAccess.dll", SetLastError:=T rue)> _
Public Shared Sub SetLongVal(ByRe f temp As GetLongRTS)
End Sub

It returns void... So that is a Sub in VB - not a

function, which
probably explains the variant error. If you still have

troubles, then
you may want to post your questions to the framework

interop group. I
know a bit about using marshalling in the framework, but

I don't have
any experience at all with the compact framework. You

might have better
luck over there if this doesn't solve it.

--
Tom Shelton
[MVP - Visual Basic]
.


Thanks again for all the help. I guess the main thing we
were looking for was passing pointers into a C library
from VB. We read that Structures in VB could only be
passed by value and were unsure how to proceed. Your
help is very much appreciated.

Denis


Actually, it's the other way around... Structures can only be passed
ByRef. So, you always get a pointer :)

Someday, I'm going to have to actually play with the compact
framework...

--
Tom Shelton
MVP [Visual Basic]
Nov 20 '05 #8
-----Original Message-----
On 2003-11-21, Tom Shelton <to*@lsnfcdm.co m> wrote:
On 2003-11-21, Denis C <an*******@disc ussions.microso ft.com> wrote:

-----Original Message-----
On 2003-11-21, Bryan G
<an*******@d iscussions.micr osoft.com> wrote:
<snip>

Ok, something to work with :). And I see a couple of things already...


And now that I know this is for the compact framework,

things are alittle different. I'm not a great expert there, but I believe that thecalling convention is Cdecl there... So, you can disregard that.Actually looking closer, I thinkg the problem is with your declarationof SetLongVal....
DBACCESSDLL_API void __cdecl SetLongVal(GetL ongRT temp) { temp->sval = 'b';
}


<DllImport("DB Access.dll", SetLastError:=T rue)> _
Public Shared Sub SetLongVal(ByRe f temp As GetLongRTS)
End Sub

It returns void... So that is a Sub in VB - not a

function, whichprobably explains the variant error. If you still have troubles, thenyou may want to post your questions to the framework interop group. Iknow a bit about using marshalling in the framework, but I don't haveany experience at all with the compact framework. You might have betterluck over there if this doesn't solve it.

--
Tom Shelton
[MVP - Visual Basic]
.


Thanks for all the help Tom, you've already saved us a lot
of grief and headaches :)
Nov 20 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
3426
by: Seung-Uk Oh | last post by:
Hi, everyone! We are developing an application using both C and C++. We have defined a structure in a C program as follows: typedef struct node { struct node *next; int value; }List;
8
4116
by: kalinga1234 | last post by:
there is a problem regarding passing array of characters to another function(without using structures,pointer etc,).can anybody help me to solve the problem.
3
2174
by: Christian F | last post by:
Hi, I'm a C-newbie and I would like to know if I am doing something wrong in the code below. It is working, but I'm afraid it might not be correct because I don't really understand everything of it. There are lots of pointers and pointers to pointers which makes me confused. First my typedef: typedef struct { double re;
5
3129
by: Paminu | last post by:
Why make an array of pointers to structs, when it is possible to just make an array of structs? I have this struct: struct test { int a; int b;
2
6066
by: WTH | last post by:
I have a C# webservice that returns an array of struct data back to a calling client. It works fine when tested via the ASMX page; however, I don't know how to make the call to this particular method from C++. If my web method is declared as: public MyStruct GetData()
3
2381
by: sd2004 | last post by:
I am still learning, could someone show/explain to me how to fix the error. I can see it is being wrong but do not know how to fix. could you also recommend a book that I can ref. to ? ////////////////// ERROR MESSAGE ///////////////////// bash-2.05b$ g++ test5c.cpp test5c.cpp: In function `int main()': test5c.cpp:36: error: invalid initialization of reference of type
17
3481
by: Johan Tibell | last post by:
Could someone outline the pros and cons of typedefing pointers to structs like this? typedef struct exp_ { int val; struct exp_ *child; } *exp; (This is straight from memory so it might not even compile.)
9
1542
by: nolonger | last post by:
Sample code:- typedef struct __Y { int a; char b; } Y; Y my_struct; Y *my_ptr_struct;
0
1659
by: mjaaland | last post by:
Hi! I've been working with DLLimports passing structs and various other parameters to unmanaged code. I had problems earlier sending pointer to structs to the unmanaged code, and this forum solved it for me (using the ref keyword etc). I now encountered a function that takes a pointer to an array as a parameter, and this array consists of other pointers, to structs. Horrible isn't it? I have no way of modifying the unmanaged code, I...
0
9489
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9298
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10072
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9906
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9885
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9737
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8737
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5172
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5329
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.