473,811 Members | 2,038 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

AccessViolation Exception - passing Structures between Unmanaged and Managed Code

6 New Member
I have a problem trying to pass a structure to an unmanaged c++ DLL from C#. When I call PCSBSpecifyPilo tLogon from C#, it throws an AccessViolation Exception
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
This is what I have...

The exported C++ DLL Function;

Expand|Select|Wrap|Line Numbers
  1. __declspec(dllexport) void PCSBSpecifyATCLogon(PCSBSessionID, const char * inServer, unsigned short inPort, const char * inID, const char * inPassword, const PCSBATCConnection_t * inInfo);
And the C++ structure;
Expand|Select|Wrap|Line Numbers
  1. typedef struct 
  2. {
  3. const char * callsign; 
  4. const char * name; 
  5. PCSBRating rating;
  6. } PCSBATCConnection_t;
The PCSBRating is just an Enum.

In C# I want to call the function to the unmanaged C++ DLL;
Expand|Select|Wrap|Line Numbers
  1. [DllImport("PCSB.dll")]
  2. private static extern void PCSBSpecifyATCLogon(IntPtr SessionID, string ServerAddr, ushort Port, string ID, string Password, [MarshalAs(UnmanagedType.Struct)] PCSBATCConnection ATC);
And the C# Structure; ... Even tried using MarshalAs, with no success.

Expand|Select|Wrap|Line Numbers
  1. [StructLayout(LayoutKind.Sequential)]
  2.         public struct PCSBATCConnection
  3.         {
  4.             //[MarshalAs(UnmanagedType.LPTStr)]
  5.             public string callsign;
  6.             //[MarshalAs(UnmanagedType.LPTStr)]
  7.             public string name;
  8.             [MarshalAs(UnmanagedType.U4)]
  9.             public PCSBATCRating rating;
  10.         }
It would be greatfull if somebody could spot what I am doing wrong...

Many thanks

Craig
Mar 17 '09 #1
5 10886
tlhintoq
3,525 Recognized Expert Specialist
While the C++ Dll issue is out of my area I just wanted to acknowledge how nice it is to see someone post such a complete, well worded message, with great use of both [quote] and [code] tags. And only your second post too! Great example to others.

By the way, I do notice that the C++ function is expecting pointers for some things...
Expand|Select|Wrap|Line Numbers
  1. const char * inServer
but you are calling it by passing it a string variable instead of a pointer to a character array.
Expand|Select|Wrap|Line Numbers
  1. string ServerAddr
so I'm going to guess that your real string is being interpreted as the address of a memory space to a character array and that is going South on ya'
Mar 17 '09 #2
craig1231
6 New Member
Hehe you wouldn't believe how long it took to write. I hope its clear enough. I use a similar function without structures, that passes strings and numbers fine. Its just when I pass structures that it comes up with the Exception. Does it have something to do with the way the struct is Marshalled?

Having made a test program to send an unmanaged struct to a c++ function, it works, but I am still confused as to why it doesnt work in the program I want it to. Is it because I am using multiple instances of the class?

Craig
Mar 17 '09 #3
tlhintoq
3,525 Recognized Expert Specialist
Good or bad is a matter of perspective, but I'm not having to deal with legacy C++ DLL's from earlier versions. Instead I have been given free range to write everything new, fresh from scratch.

The only places I've dealt with DLL issues is for hardware from vendors and I've been lucky enough to not have to deal with marshalling at all.

Anyone else reading this with more experience at it please jump in.
Mar 17 '09 #4
alexgm23
6 New Member
Hi Craig,

I hope this can be useful for you:

DLL Code
Expand|Select|Wrap|Line Numbers
  1. // msgbox.dll
  2.  
  3. typedef struct MsgBoxData
  4. {
  5.     const char * Text;
  6.     int Options;
  7. } ExchStruct;
  8.  
  9. extern "C" __declspec(dllexport) void MsgBox(const char * Title, const MsgBoxData * Data);
  10.  
  11. void MsgBox(const char * Title, const MsgBoxData * Data)
  12. {
  13.     MessageBox(NULL, Data->Text, Title, Data->Options);
  14. }
  15.  
C# Code
Expand|Select|Wrap|Line Numbers
  1. public partial class Form1 : Form
  2. {
  3.     public Form1()
  4.     {
  5.         InitializeComponent();
  6.     }
  7.  
  8.     [StructLayout(LayoutKind.Sequential)]
  9.     public struct MsgBoxData
  10.     {
  11.         public IntPtr Text;
  12.         public Int32 Options;
  13.     }
  14.  
  15.     [DllImport("msgbox.dll", CallingConvention = CallingConvention.Cdecl)]
  16.     public extern static void MsgBox(
  17.         [MarshalAs(UnmanagedType.LPStr)] String Title,
  18.         [MarshalAs(UnmanagedType.SysInt)] IntPtr Data
  19.         );
  20.  
  21.     private void button1_Click(object sender, EventArgs e)
  22.     {
  23.         MsgBoxData msg = new MsgBoxData();
  24.         msg.Text = Marshal.StringToHGlobalAnsi(textBox2.Text);
  25.         msg.Options = 0;
  26.         IntPtr ptrmsg = Marshal.AllocHGlobal(Marshal.SizeOf(msg));
  27.         Marshal.StructureToPtr(msg, ptrmsg, true);
  28.         MsgBox(textBox1.Text, ptrmsg);
  29.     }
  30. }
  31.  
  32.  
If you need to pass a struct pointer as a parameter you need to allocate som memory for it first:

Expand|Select|Wrap|Line Numbers
  1.     IntPtr ptrmsg = Marshal.AllocHGlobal(Marshal.SizeOf(msg));
  2.     Marshal.StructureToPtr(msg, ptrmsg, true);
  3.  
Alex G.
Mar 17 '09 #5
craig1231
6 New Member
Hey, that works, thanks Alex! I only had to allocate the structure in memory. However I have a new problem... which I shall start a new thread... regarding callbacks and garbage colllection.

Craig
Mar 18 '09 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

1
3561
by: lolomgwtf | last post by:
I have a managed C++ method that wraps unmanaged code and creates a managed object holding data retrieved form an unmanged one. I want create an instance of this managed class in C#, pass it to this method and have it set the instance to hold the right data. >From what I've read it seems I should be able to pass C# objects to managed C++ methods and it should just work; however, when I try it, my C# instance comes out null. If I step...
33
3878
by: Peter Seaman | last post by:
I understand that structures are value types and arrays and classes are reference types. But what about arrays as members of structures i.e. as in C struct x { int n; int a; }
5
7209
by: GeRmIc | last post by:
Hi, I am doing an interop from unmanaged code to C#. How do i pass an ArrayList pointer from an unmanaged code, (structres are easily passed by between C# and C). //This is the C code NameStruct lnames; //This is a structure in C#
2
4683
by: lolomgwtf | last post by:
I have a managed C++ method that wraps unmanaged code and creates a managed object holding data retrieved form an unmanged one. I want create an instance of this managed class in C#, pass it to this method and have it set the instance to hold the right data. >From what I've read it seems I should be able to pass C# objects to managed C++ methods and it should just work; however, when I try it, my C# instance comes out null. If I step...
17
3688
by: mr.resistor | last post by:
hey i am having a few problems calling a C DLL from C#. i am using a simple function that takes an array of floats and an integer as an input, but i cannot seem to get it to work. when i try to compile i get the following error: Attempted to read or write protected memory the C function should not be manipulating the input arra, only reading
0
2021
by: Haxan | last post by:
Hi, I have an unmanaged application that converts a function pointer to a delegate and then pass this as a parameter(delegate) to a managed function which then invokes it. Currently Im able to jump to this unmanaged function, but the values of the parameters inside this function Im seeing are not correct(they have some garbage values). //unmanaged class (C++ application)
20
1487
by: djc | last post by:
I get this *intermittently* on a utility I am working on. I don't know whats going on but here are a few points about it: - using VS 2005, running on xp sp2 - program uses multiple threadpool threads - only happens when built with the 'release' configuration (no debug flag, compiler optimizations in effect) - no problems in debug config here is the error: Unhandled Exception: System.AccessViolationException: Attempted to read or write...
17
7263
by: =?Utf-8?B?U2hhcm9u?= | last post by:
Hi Gurus, I need to transfer a jagged array of byte by reference to unmanaged function, The unmanaged code should changed the values of the array, and when the unmanaged function returns I need to show the array data to the end user. Can I do that? How?
6
3884
by: Andy Baker | last post by:
I am attempting to write a .NET wrapper for a C++ DLL file, but am having problems with passing strings as parameters. How should I be writing my C# function call when the C header file is definined as taking a char * as an argument? For example the C++ header says SDCERR GetCurrentConfig(DWORD *num, char *name); I am using Uint for the *num parameter, which returns the correct value but for *name, I always get back a string of 6 squares....
0
9605
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
10389
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...
0
9205
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...
1
7670
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6890
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5554
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...
1
4339
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3867
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3018
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.