473,804 Members | 3,380 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

P/Invoke and out parameter

I'm having a problem with something I thought was quite simple.

I have a function in a C DLL. Let's call it SomeFunction. This is the
prototype for SomeFunction:

void SomeFunction(ch ar * anArrayOfChars) ;

where anArrayOfChars is an out parameter.

I thought all I had to do was declare it as follows:

[DllImport("some DLL", CharSet = CharSet.Auto)]
public static extern void SomeFunction(St ringBuilder sBuf)
and within the Main function call it like that:

StringBuilder sBuf = new StringBuilder(1 28);
SomeFunction(sB uf);

And I should have an sBuf that was filled by some function.
Unfortunately, I'm getting the following exception:

Object Reference not set to an instance of an object. Any ideas what I'm
doing wrong?

In case you wonder, SomeFunction just does a strcpy(anArrayO fChars,
"Hello, World!);

Thanks in advance.
Nov 16 '05 #1
14 6148
I thought all I had to do was declare it as follows:

[DllImport("some DLL", CharSet = CharSet.Auto)]
public static extern void SomeFunction(St ringBuilder sBuf)


You should be using CharSet.Ansi rather than CharSet.Auto here. I
don't know if that would cause such an exception though.

Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Nov 16 '05 #2


"Pollux" <po****@nospam. spam> wrote in message
news:MP******** *************** *@usenet.plus.n et...
I'm having a problem with something I thought was quite simple.

I have a function in a C DLL. Let's call it SomeFunction. This is the
prototype for SomeFunction:

void SomeFunction(ch ar * anArrayOfChars) ;

where anArrayOfChars is an out parameter.

I thought all I had to do was declare it as follows:

[DllImport("some DLL", CharSet = CharSet.Auto)]
public static extern void SomeFunction(St ringBuilder sBuf)
and within the Main function call it like that:

StringBuilder sBuf = new StringBuilder(1 28);
SomeFunction(sB uf);

And I should have an sBuf that was filled by some function.
Unfortunately, I'm getting the following exception:

Object Reference not set to an instance of an object. Any ideas what I'm
doing wrong?

In case you wonder, SomeFunction just does a strcpy(anArrayO fChars,
"Hello, World!);

Thanks in advance.


The exception is obviously not thrown by the call of SomeFunction. Could you
provide a call stack dump?

Because you return an ansi string, you need to change your signature into:
[DllImport("some DLL")]
public static extern void
SomeFunction([MarshalAs(Unman agedType.LPStr)]StringBuilder sBuf)

Willy.
Nov 16 '05 #3
In article <#T************ **@TK2MSFTNGP15 .phx.gbl>,
wi************* @pandora.be says...


"Pollux" <po****@nospam. spam> wrote in message
news:MP******** *************** *@usenet.plus.n et...
I'm having a problem with something I thought was quite simple.

I have a function in a C DLL. Let's call it SomeFunction. This is the
prototype for SomeFunction:

void SomeFunction(ch ar * anArrayOfChars) ;

where anArrayOfChars is an out parameter.

I thought all I had to do was declare it as follows:

[DllImport("some DLL", CharSet = CharSet.Auto)]
public static extern void SomeFunction(St ringBuilder sBuf)
and within the Main function call it like that:

StringBuilder sBuf = new StringBuilder(1 28);
SomeFunction(sB uf);

And I should have an sBuf that was filled by some function.
Unfortunately, I'm getting the following exception:

Object Reference not set to an instance of an object. Any ideas what I'm
doing wrong?

In case you wonder, SomeFunction just does a strcpy(anArrayO fChars,
"Hello, World!);

Thanks in advance.


The exception is obviously not thrown by the call of SomeFunction. Could you
provide a call stack dump?

Because you return an ansi string, you need to change your signature into:
[DllImport("some DLL")]
public static extern void
SomeFunction([MarshalAs(Unman agedType.LPStr)]StringBuilder sBuf)

Willy.


Hi Willy,

Sorry about that, I should have mentioned this. The call stack suggests
that the exception was thrown from SomeFunction. If i remove the strcpy
statment and simply return or display a messagebox, I don't get an
exception.

I would guess that somehow the char * doesn't point to a valid memory
address, but I'm not sure why this would be hapenning since the
Framework should take care of this for me right?
Nov 16 '05 #4


"Pollux" <po****@nospam. spam> wrote in message
news:MP******** *************** *@usenet.plus.n et...
In article <#T************ **@TK2MSFTNGP15 .phx.gbl>,
wi************* @pandora.be says...


Sorry about that, I should have mentioned this. The call stack suggests
that the exception was thrown from SomeFunction. If i remove the strcpy
statment and simply return or display a messagebox, I don't get an
exception.

I would guess that somehow the char * doesn't point to a valid memory
address, but I'm not sure why this would be hapenning since the
Framework should take care of this for me right?


I assume this is not exactly what you are doing in your C function (missing
quote).
strcpy(anArrayO fChars,
"Hello, World!);


Could you post the exact C code function?

Willy.
Nov 16 '05 #5
In article <#T************ **@TK2MSFTNGP15 .phx.gbl>,
wi************* @pandora.be says...


"Pollux" <po****@nospam. spam> wrote in message
news:MP******** *************** *@usenet.plus.n et...
I'm having a problem with something I thought was quite simple.

I have a function in a C DLL. Let's call it SomeFunction. This is the
prototype for SomeFunction:

void SomeFunction(ch ar * anArrayOfChars) ;

where anArrayOfChars is an out parameter.

I thought all I had to do was declare it as follows:

[DllImport("some DLL", CharSet = CharSet.Auto)]
public static extern void SomeFunction(St ringBuilder sBuf)
and within the Main function call it like that:

StringBuilder sBuf = new StringBuilder(1 28);
SomeFunction(sB uf);

And I should have an sBuf that was filled by some function.
Unfortunately, I'm getting the following exception:

Object Reference not set to an instance of an object. Any ideas what I'm
doing wrong?

In case you wonder, SomeFunction just does a strcpy(anArrayO fChars,
"Hello, World!);

Thanks in advance.


The exception is obviously not thrown by the call of SomeFunction. Could you
provide a call stack dump?

Because you return an ansi string, you need to change your signature into:
[DllImport("some DLL")]
public static extern void
SomeFunction([MarshalAs(Unman agedType.LPStr)]StringBuilder sBuf)

Willy.


Ok, I might not have given you the whole picture. I just tried doing a
simple program with just the function I mentioned from scratch and it
all worked fine. I didn't even need to specify the Charset property or
use [MarshalAs(Unman agedType.LPStr)]. I passed in a StringBuilder and it
was correctly filled by the C function.

The problem I'm experiencing is hapenning on a C dll that was created
some time ago.

I have have modified the function I'm calling to just do a strcpy and
return to simplify testing, so it is pretty much the same as my test
function.

The Call Stack wasn't all that useful in that it points to the offendin
C function which we know shouldn't be returning an exception.

I have tried passing a simple string to the function in the DLL and
displaying it in a Messagebox and that comes out as empty, so there is
definitely a problem there.

I can only assume that the problem must be with the project options in
either the C# program (unlikely I suspect) or the C dll. Any ideas what
that might be?

Thanks for your help and sorry for the confusion.
Nov 16 '05 #6
Does the unmanaged function use the cdecl calling convention? P?Invoke defaults to winapi

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk

Ok, I might not have given you the whole picture. I just tried doing a
simple program with just the function I mentioned from scratch and it
all worked fine. I didn't even need to specify the Charset property or
use [MarshalAs(Unman agedType.LPStr)]. I passed in a StringBuilder and it
was correctly filled by the C function.

The problem I'm experiencing is hapenning on a C dll that was created
some time ago.

I have have modified the function I'm calling to just do a strcpy and
return to simplify testing, so it is pretty much the same as my test
function.

The Call Stack wasn't all that useful in that it points to the offendin
C function which we know shouldn't be returning an exception.

I have tried passing a simple string to the function in the DLL and
displaying it in a Messagebox and that comes out as empty, so there is
definitely a problem there.

I can only assume that the problem must be with the project options in
either the C# program (unlikely I suspect) or the C dll. Any ideas what
that might be?

Thanks for your help and sorry for the confusion.

Nov 16 '05 #7
In article <es************ **@TK2MSFTNGP09 .phx.gbl>,
ri******@NOSPAM develop.com says...
Does the unmanaged function use the cdecl calling convention? P?Invoke defaults to winapi

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk

Ok, I might not have given you the whole picture. I just tried doing a
simple program with just the function I mentioned from scratch and it
all worked fine. I didn't even need to specify the Charset property or
use [MarshalAs(Unman agedType.LPStr)]. I passed in a StringBuilder and it
was correctly filled by the C function.

The problem I'm experiencing is hapenning on a C dll that was created
some time ago.

I have have modified the function I'm calling to just do a strcpy and
return to simplify testing, so it is pretty much the same as my test
function.

The Call Stack wasn't all that useful in that it points to the offendin
C function which we know shouldn't be returning an exception.

I have tried passing a simple string to the function in the DLL and
displaying it in a Messagebox and that comes out as empty, so there is
definitely a problem there.

I can only assume that the problem must be with the project options in
either the C# program (unlikely I suspect) or the C dll. Any ideas what
that might be?

Thanks for your help and sorry for the confusion.


Unfortunately I have thought about this. Both my test dll and my work
dll use the cdecl calling convention, but the framework seems to manage
calling the test dll just fine without me having to specify anything. I
tried manually specifying the calling convention but that didn't help
either. Could it be that the framework defaults to cdecl?

Anyway I think if I was using the wrong calling convetion, the problem
would be that it couldn't find the entry point whereas here it can in
both cases.

Thanks for your help.
Nov 16 '05 #8

"Pollux" <po****@nospam. spam> wrote in message
news:MP******** *************** @usenet.plus.ne t...
Ok, I might not have given you the whole picture. I just tried doing a
simple program with just the function I mentioned from scratch and it
all worked fine. I didn't even need to specify the Charset property or
use [MarshalAs(Unman agedType.LPStr)]. I passed in a StringBuilder and it
was correctly filled by the C function.

The problem I'm experiencing is hapenning on a C dll that was created
some time ago.

I have have modified the function I'm calling to just do a strcpy and
return to simplify testing, so it is pretty much the same as my test
function.

The Call Stack wasn't all that useful in that it points to the offendin
C function which we know shouldn't be returning an exception.

I have tried passing a simple string to the function in the DLL and
displaying it in a Messagebox and that comes out as empty, so there is
definitely a problem there.

I can only assume that the problem must be with the project options in
either the C# program (unlikely I suspect) or the C dll. Any ideas what
that might be?

Thanks for your help and sorry for the confusion.


True, the MarshalAs attribute is not needed as it's the PInvoke interop's
default.
The calling convention is __stdcall by default, and you better change your C
function signature or you specify the CallingConventi on.Cdecl attribute
accordingly, failing to do so may corrupt the call stack.
Also make sure you Stringbuilder buffer is large enough to contain the
string.

Willy.
Nov 16 '05 #9
In article <Om************ **@TK2MSFTNGP11 .phx.gbl>,
wi************* @pandora.be says...

"Pollux" <po****@nospam. spam> wrote in message
news:MP******** *************** @usenet.plus.ne t...
Ok, I might not have given you the whole picture. I just tried doing a
simple program with just the function I mentioned from scratch and it
all worked fine. I didn't even need to specify the Charset property or
use [MarshalAs(Unman agedType.LPStr)]. I passed in a StringBuilder and it
was correctly filled by the C function.

The problem I'm experiencing is hapenning on a C dll that was created
some time ago.

I have have modified the function I'm calling to just do a strcpy and
return to simplify testing, so it is pretty much the same as my test
function.

The Call Stack wasn't all that useful in that it points to the offendin
C function which we know shouldn't be returning an exception.

I have tried passing a simple string to the function in the DLL and
displaying it in a Messagebox and that comes out as empty, so there is
definitely a problem there.

I can only assume that the problem must be with the project options in
either the C# program (unlikely I suspect) or the C dll. Any ideas what
that might be?

Thanks for your help and sorry for the confusion.


True, the MarshalAs attribute is not needed as it's the PInvoke interop's
default.
The calling convention is __stdcall by default, and you better change your C
function signature or you specify the CallingConventi on.Cdecl attribute
accordingly, failing to do so may corrupt the call stack.
Also make sure you Stringbuilder buffer is large enough to contain the
string.

Willy.


Unfortunately changing the calling convention to cdecl didn't solve it,
though it is probably a good thing to have set!

As I said, the when I created a dll with the functions that I mentioned
in my original post, I was sucessful in getting the C function in
filling the buffer.

This is what I have in my C# program:

[DllImport("some dll", CallingConventi on=CallingConve ntion.Cdecl)]
public static extern void SomeFunction(lo ng aLong,
[MarshalAs(Unman agedType.LPStr)] StringBuilder aBuffer, [MarshalAs
(UnmanagedType. LPStr)] StringBuilder anotherBuffer);

The call to the function is as follows:

long aLong = 1;
StringBuilder aBuffer = new StringBuilder(1 28); //This size should be
more than ample
StringBuilder anotherBuffer = new StringBuilder(1 28);

SomeFunction(aL ong, aBuffer, anotherBuffer);

The C function is as follow:

extern "C" __declspec(dlle xport) void SomeFunction(lo ng aLong, char
*aBuffer, char * anotherBuffer)
{
strcpy(aBuffer, "Hello");
strcpy(anotherB uffer, "Hello");
}

Note that I didn't copy and paste so there might be a typo or two, but
it compiles fine! :-)
Nov 16 '05 #10

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

Similar topics

2
3772
by: Marcin | last post by:
Hello! Is there any method to detect parameters values passed to called method? For example: public Guid ApplicationLogin(string userName, string password, int dbId)
7
1448
by: Richard Cavell | last post by:
Hi, The point of using const on a parameter to a function should be to let your compiler know that the parameter shouldn't be modified during your program. This allows you to keep your code safe and bug-free. Now, it also occurs to me that a const something-or-other could be passed as a reference (since it's guaranteed not to change) , or that the address of the object could be passed rather than the whole thing in the case of a...
0
4390
by: PJ | last post by:
Hello, I am trying to use late binding to call a COM object. I am trying to call a 'GetTables' method on the object. It's essentially a 'MetadataService' which is used to return the names of tables which are in a specific database. the first parameter to GetTables is "in only" (it's a
13
7437
by: Christian Westerlund | last post by:
Hi! I'm trying to use P/Invoke and a Method which takes an IntPtr where I am supposed to put an address to a method which the native method will use to communicate back to me. How do I convert a method to an IntPtr? / Christian
16
3761
by: Stefan Hong | last post by:
Hi, It seems that the way reflection resolves methods is not quite the same as default CLR. For example this simple class: class Test { public void Hello(string name) { Console.WriteLine("Hello(string)"); } public void Hello(object obj) {
14
7355
by: stic | last post by:
Hi, I'm in a middle of writing something like 'exception handler wraper' for a set of different methodes. The case is that I have ca. 40 methods form web servicem, with different return values (and types), and with out parmeters. What I want to do is to support each method call with exception (http 404, soap exception, and other types of exceptions) and wrap it with try & catch (a lots of catch ;-)
2
269
by: dani kotlar | last post by:
Is it possible to pass the Invoke or BeginInvoke functions as a parameter a delegate encapsulating a function with a non empty set of parameters? How is it done?
0
7820
by: Sivajee Akula | last post by:
Hello All, I am trying to consume a .NET Service from Adobe LiveCycle Workflow. The service deals with complex objects. I am getting the following exception at the time of invocation of the service, and due to which my workflow gets stalled. When I searched the net, I found many posts reporting this error, but none with a solution. There is no code involved in the invocation, everything is handled by Adobe tool itself. I just specify the...
6
39439
by: Dom | last post by:
I'm teaching myself about delegates and the Invoke method, and I have a few newbie questions for the gurus out there: Here are some CSharp statements: 1. public delegate void MyDelegate (int k, string s) 2. MyDelegate MyDelegateVar = MyMethod 3. MyForm.Invoke (MyDelegateVar) Some questions:
10
2135
by: vcquestions | last post by:
Hi. Is there way to have a function pointer to a delegate in c++/cli that would allow me to pass delegates with the same signatures as parameters to a method? I'm working with managed code. Let's say we have 2 delegates: public delegate void FirstDelegate( int i ); public delegate void SecondDelegate( int i );
0
9706
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
9579
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,...
1
10319
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
10076
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
9144
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
6851
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
5520
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...
2
3816
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2990
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.