473,387 Members | 1,398 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Return string from C++

MRe
Hi,

I have a C++ function that takes an allocated char* array in, which it
will copy into, and return. I need to be able to access what was copied into
this array in a csharp program. So far I have this...

C++
void test(char* pOut)
{ CopyMemory(pOut, "abc", 3);
}

C#
[DllImport("test.dll", CharSet=CharSet.Auto)]
private static extern void test([MarshalAs(UnmanagedType.LPStr)] out string
Result);

public string RunTest()
{
StringBuilder sb = new StringBuilder(3, 3);
string Buffer;
// Create space in string - is there a better way to do this?
for(int Index = 0; Index < 3; Index++)
sb.Append(' ');
Buffer = sb.ToString();
test(out Buffer);
return Buffer;
}

But all I get is a System.NullReferenceException.

What's going on please?

Thank you,
Regards,
Eliott
Nov 17 '05 #1
5 4677
MRe wrote:
C++
void test(char* pOut)
{ CopyMemory(pOut, "abc", 3);
}

C#
[DllImport("test.dll", CharSet=CharSet.Auto)]
private static extern void test([MarshalAs(UnmanagedType.LPStr)] out string
Result);

public string RunTest()
{
StringBuilder sb = new StringBuilder(3, 3);
string Buffer;
for(int Index = 0; Index < 3; Index++)
sb.Append(' ');
Buffer = sb.ToString();
// Create space in string - is there a better way to do this?
Yes. string Buffer = new String(' ', 3);
test(out Buffer);
return Buffer;
}

But all I get is a System.NullReferenceException.

What's going on please?


My **guess** is that you want to pass the Buffer as a "ref", not an
"out".

(It might also have something to do with converting 16-byte char
strings to 8-byte char strings and back.)

--

www.midnightbeach.com
Nov 17 '05 #2
> void test(char* pOut)
{ CopyMemory(pOut, "abc", 3);
}
Depending on your implementation of CopyMemory, this may not append a zero
terminator for the string.
C#
[DllImport("test.dll", CharSet=CharSet.Auto)]
private static extern void test([MarshalAs(UnmanagedType.LPStr)] out
string
Result);
Instread of an "out" parameter, just pass a StringBuilder:

private static extern void test(
[MarshalAs(UnmanagedType.LPStr)] StringBuilder Result );
StringBuilder sb = new StringBuilder(3, 3);
string Buffer;
// Create space in string - is there a better way to do this?
for(int Index = 0; Index < 3; Index++)
sb.Append(' ');
Buffer = sb.ToString();
Since the DLL is not using the characters, there's no need to fill the
string with spaces. Just make sure there's enough capacity for the result
by replacing the above with:

StringBuilder sb = new StringBuilder(3);
test(out Buffer);
Now that we're using StringBuilder, the "out" modifier is no longer
required:

test(Buffer);
But all I get is a System.NullReferenceException.

There are many things in the code that might go wrong, but I don't see a
cause for NullReferenceException? Perhaps you can share the line of code
that raises the exception.

Greetings,
Wessel
Nov 17 '05 #3
You should always use a StringBuilder to return strings from unmanaged code. .NET assumes strings are immutable and optimizes based on this. You should not allow unmanaged code to alter the contents of a string.

This is essentially the same issue as this

http://blogs.msdn.com/brada/archive/...03/148144.aspx

Regards

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

MRe wrote:
C++
void test(char* pOut)
{ CopyMemory(pOut, "abc", 3);
}

C#
[DllImport("test.dll", CharSet=CharSet.Auto)]
private static extern void test([MarshalAs(UnmanagedType.LPStr)] out string
Result);

public string RunTest()
{
StringBuilder sb = new StringBuilder(3, 3);
string Buffer;
for(int Index = 0; Index < 3; Index++)
sb.Append(' ');
Buffer = sb.ToString();
// Create space in string - is there a better way to do this?
Yes. string Buffer = new String(' ', 3);
test(out Buffer);
return Buffer;
}

But all I get is a System.NullReferenceException.

What's going on please?


My **guess** is that you want to pass the Buffer as a "ref", not an
"out".

(It might also have something to do with converting 16-byte char
strings to 8-byte char strings and back.)

--

www.midnightbeach.com

[microsoft.public.dotnet.languages.csharp]
Nov 17 '05 #4
MRe
Thank you all for your help - especially Wessel, your help was completely
hassle free (it's working now).
There are many things in the code that might go wrong, but I don't see a
cause for NullReferenceException? Perhaps you can share the line of code
that raises the exception.


The test being a simplified version of my problem, the actual code-line of
failure was

codaRead(m_hCoda, Id, Buffer, Length);

Only difference between this and the sample test; the Buffer size is
dynamic. The other three variables I know to be right and the C++ code works
when accessed by other languages. I guess it probably doesn't really matter
anyways, now that it's working with the StringBuilder.

Thank you again,
Regards,
Eliott
Nov 17 '05 #5
"Richard Blewett [DevelopMentor]" wrote:
http://blogs.msdn.com/brada/archive/...03/148144.aspx


Interesting, thanks. Now I've learned something before breakfast!

--

www.midnightbeach.com
Nov 17 '05 #6

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

Similar topics

3
by: Phil Powell | last post by:
My first time working with a PHP class, and after 6 hours of working out the kinks I am unable to return a value from the class, so now I appeal to the general audience what on earth did I do wrong...
12
by: Jose Fernandez | last post by:
Hello. I'm building a web service and I get this error. NEWS.News.CoverNews(string)': not all code paths return a value This is the WebMethod public SqlDataReader CoverNews(string Sport)...
12
by: Michael Maes | last post by:
Hello, I have a BaseClass and many Classes which all inherit (directly) from the BaseClass. One of the functions in the BaseClass is to (de)serialize the (inherited) Class to/from disk. ...
7
by: nafri | last post by:
hello all, I want to create a function that returns the first element of the Array that is input to it. However, the Input Array can be an Array of points, double, or anyother type, which means...
16
by: Dany | last post by:
Our web service was working fine until we installed .net Framework 1.1 service pack 1. Uninstalling SP1 is not an option because our largest customer says service packs marked as "critical" by...
9
by: MSDNAndi | last post by:
Hi, I have a set of simple webservices calls that worked fine using .NET Framework 1.0. I am calling a Java/Apache based webservices, the calling side is not able to supply a proper WSDL. ...
18
by: Pedro Pinto | last post by:
Hi there once more........ Instead of showing all the code my problem is simple. I've tried to create this function: char temp(char *string){ alterString(string); return string;
2
by: utab | last post by:
Dear all, I tried sth easy(actually this was an exercise) but I tried to use the standard lib. heavily for this problem(as far as I can). There was one point I could not figure out. The problem...
6
KoreyAusTex
by: KoreyAusTex | last post by:
If anyone can help me figure out the what the missing return statements are, I think it might be the fact that I need to add a return false in the getValue()? import java.util.*; public class...
14
by: =?Utf-8?B?QmVu?= | last post by:
Hi all, I'm trying to understand the concept of returning functions from the enclosing functions. This idea is new to me and I don't understand when and why I would need to use it. Can someone...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...

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.