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; - __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; - typedef struct
-
{
-
const char * callsign;
-
const char * name;
-
PCSBRating rating;
-
} PCSBATCConnection_t;
The PCSBRating is just an Enum. In C# I want to call the function to the unmanaged C++ DLL; -
[DllImport("PCSB.dll")]
-
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. - [StructLayout(LayoutKind.Sequential)]
-
public struct PCSBATCConnection
-
{
-
//[MarshalAs(UnmanagedType.LPTStr)]
-
public string callsign;
-
//[MarshalAs(UnmanagedType.LPTStr)]
-
public string name;
-
[MarshalAs(UnmanagedType.U4)]
-
public PCSBATCRating rating;
-
}
It would be greatfull if somebody could spot what I am doing wrong...
Many thanks
Craig
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...
but you are calling it by passing it a string variable instead of a pointer to a character array.
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'
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
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.
Hi Craig,
I hope this can be useful for you: DLL Code -
// msgbox.dll
-
-
typedef struct MsgBoxData
-
{
-
const char * Text;
-
int Options;
-
} ExchStruct;
-
-
extern "C" __declspec(dllexport) void MsgBox(const char * Title, const MsgBoxData * Data);
-
-
void MsgBox(const char * Title, const MsgBoxData * Data)
-
{
-
MessageBox(NULL, Data->Text, Title, Data->Options);
-
}
-
C# Code -
public partial class Form1 : Form
-
{
-
public Form1()
-
{
-
InitializeComponent();
-
}
-
-
[StructLayout(LayoutKind.Sequential)]
-
public struct MsgBoxData
-
{
-
public IntPtr Text;
-
public Int32 Options;
-
}
-
-
[DllImport("msgbox.dll", CallingConvention = CallingConvention.Cdecl)]
-
public extern static void MsgBox(
-
[MarshalAs(UnmanagedType.LPStr)] String Title,
-
[MarshalAs(UnmanagedType.SysInt)] IntPtr Data
-
);
-
-
private void button1_Click(object sender, EventArgs e)
-
{
-
MsgBoxData msg = new MsgBoxData();
-
msg.Text = Marshal.StringToHGlobalAnsi(textBox2.Text);
-
msg.Options = 0;
-
IntPtr ptrmsg = Marshal.AllocHGlobal(Marshal.SizeOf(msg));
-
Marshal.StructureToPtr(msg, ptrmsg, true);
-
MsgBox(textBox1.Text, ptrmsg);
-
}
-
}
-
-
If you need to pass a struct pointer as a parameter you need to allocate som memory for it first: -
IntPtr ptrmsg = Marshal.AllocHGlobal(Marshal.SizeOf(msg));
-
Marshal.StructureToPtr(msg, ptrmsg, true);
-
Alex G.
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
Sign in to post your reply or Sign up for a free account.
Similar topics |
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...
|
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;
}
|
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#
|
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...
|
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
| |
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)
|
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...
|
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?
|
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....
|
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,...
|
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...
| |
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...
|
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...
|
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();...
|
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...
|
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
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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...
| |