Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / .NET Framework / CLR / September 2003

Tip: Looking for answers? Try searching our database.

passing a struct by ref to unmanged code

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
codymanix - 22 Sep 2003 22:36 GMT
i want to pass a struct by reference to a function in a c++ dll.

the problem is that the call causes an ArgumentException in the calling c#
code.
i already tried to use "out" instead of "ref" there was no exception
generated but i
saw in the unmanaged code all fields of the struct were uninitialized!
this is my c# code:

[StructLayout(LayoutKind.Sequential,Pack=1)]
struct WorldStats
{
public ObjectStats[] stats;
public int iterations;
public int living;
public WorldStats(int n)
{
stats = new ObjectStats[n];
iterations=0;
living=0;
}
}

[DllImport("aikernel.dll", CallingConvention=CallingConvention.Winapi)]
static extern void GetWorldStats(ref WorldStats ws);

WorldStats ws = new WorldStats(this.MAXOBJECTS);
GetWorldStats(ref ws); // here is the argumentexception thrown

the function in my c++ dll is declared as follows:
__declspec(dllexport) void /*WINAPI*/__stdcall GetWorldStats(WorldStats &
ws);

#pragma pack(push,1)
struct WorldStats
{
ObjectStats * stats;
int iterations;
int living;
};
#pragma pack(pop,1)

--
cody

[Freeware, Games and Humor]
www.deutronium.de.vu || www.deutronium.tk
Mattias Sj?gren - 23 Sep 2003 01:10 GMT
>[StructLayout(LayoutKind.Sequential,Pack=1)]
>struct WorldStats
>{
>public ObjectStats[] stats;
>public int iterations;
>public int living;

The exception is likely caused by the stats member. You can't declare
it as an array, it will not marshal correctly. Try making it an IntPtr
instead, and handle the array allocation and initialization yourself.

Mattias

Signature

Mattias Sjögren [MVP]  mattias @ mvps.org
http://www.msjogren.net/dotnet/
Please reply only to the newsgroup.


Rate this thread:







Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.