473,654 Members | 3,098 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Return string from c++ dll - interop services

Hi,

I am having some trouble returning a string from a c++ dll. I tend to get
junk data back and I am not sure of the method, my code so far:

Function is declared in c++ dll 'Test' and exported like this:

extern "C" __declspec( dllexport ) BSTR getbagstr();
extern "C" __declspec( dllexport ) BSTR getbagstr() {
g.getbag()->setdisplaybag( "ZZZZZZZZZZZZZZ ZZZZZZZZZZZZZZ" );
const char * buff = g.getbag()->getdisplaybag( ).c_str();
return SysAllocStringB yteLen (buff , lstrlen(buff));
}

I want use the function via interop services - p/invoke - to display the
string in a simple c# program:

[DllImport("Test ")]
private static extern IntPtr getbagstr();

public static string getBagString()
{
return Marshal.PtrToSt ringAuto(getbag str());
}

The data I am returning is not correct. All display bag does is store and
return the string as below. I am returning int data correctly, but strings
are proving difficult. Anybody able to help?

void Bag::setdisplay bag(const string & str) {
displaybag = str;
}

string Bag::getdisplay bag() { return displaybag; }

Sep 3 '06 #1
5 9509
public static string getBagString()
{
return Marshal.PtrToSt ringAuto(getbag str());
}
SysAllocStringB yteLen returns a BSTR containing ANSI characters. So
PtrToStringAuto will only work on Win9x platforms. Try changing it to

IntPtr ptr = getbagstr();
string tmp = Marshal.PtrToSt ringAnsi(ptr);
Marshal.FreeBST R(ptr);
return s;
Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Sep 3 '06 #2
On Sun, 03 Sep 2006 23:21:35 +0200, Mattias Sjögren wrote:
> public static string getBagString()
{
return Marshal.PtrToSt ringAuto(getbag str());
}

SysAllocStringB yteLen returns a BSTR containing ANSI characters. So
PtrToStringAuto will only work on Win9x platforms. Try changing it to

IntPtr ptr = getbagstr();
string tmp = Marshal.PtrToSt ringAnsi(ptr);
Marshal.FreeBST R(ptr);
return s;
Thanks Mattias, this worked. I have been checking through the p/invoke
examples on your website which is an excellent resource. However, I
wondered if you could provide an example for this code:

extern "C" __declspec( dllexport ) __stdcall void setdisplaybag(L PSTR
tiles);
extern "C" __declspec( dllexport ) __stdcall void setdisplaybag(L PSTR
tiles) {
//set display bag code
}

Assuming the above is the exported c++ function, how should C# pass in the
BSTR safely? How should the BSTR be freed or should it?

[DllImport("Test ")]
private static extern void setdisplaybag(I ntPtr ptr);

public static void SetDisplayBag(s tring str)
{
IntPtr tmp = Marshal.StringT oBSTR(str);
setdisplaybag(t mp);
//Marshal.FreeBST R(tmp);
}
Sep 3 '06 #3
>Assuming the above is the exported c++ function, how should C# pass in the
>BSTR safely?
I see nothing about BSTRs in the function signatures, so I would
simply declare it as

static extern void setdisplaybag(s tring tiles);

Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Sep 4 '06 #4
On Tue, 05 Sep 2006 00:05:07 +0200, Mattias Sjögren wrote:
I see nothing about BSTRs in the function signatures, so I would
simply declare it as

static extern void setdisplaybag(s tring tiles);
Ok fine, but when I input this i get strange output:

settiles("ZZZZZ ZZZZYYYYYYYYYYY YYY");
Console.WriteLi ne(getbagstr()) ;

console output:

v►☺YYYYYYYY YYYYYZZZZZZZZZ

Where are the extra characters coming from at the beginning and what is
needed to avoid them? Thanks in advance.
Sep 5 '06 #5
Jason,
>Where are the extra characters coming from at the beginning and what is
needed to avoid them? Thanks in advance.
I don't know without seeing all the C++ code. It doesn't happen here.
I wrote the folowing test code and it roundtrips the string correctly.

// C++ DLL
#include <windows.h>
#pragma comment(lib, "oleaut32.l ib")

char buf[100];

extern "C"
{
__declspec(dlle xport) BSTR __stdcall getbagstr()
{
return SysAllocStringB yteLen(buf, lstrlen(buf));
}

__declspec(dlle xport) void __stdcall setdisplaybag(c har *tiles)
{
lstrcpyn(buf, tiles, 100);
}

}

// C# client
using System;
using System.Runtime. InteropServices ;

class Test
{
[DllImport("test .dll")]
static extern IntPtr getbagstr();

[DllImport("test .dll")]
static extern void setdisplaybag(s tring tiles);

static void Main()
{
setdisplaybag(" ZZZZZZZZZYYYYYY YYYYYYYY");
IntPtr p = getbagstr();
Console.WriteLi ne(Marshal.PtrT oStringAnsi(p)) ;
Marshal.FreeBST R(p);
}
}
Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Sep 7 '06 #6

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

Similar topics

11
1940
by: Tom Leylan | last post by:
(I posted this in languages.vb also... I can't figure out where things go if you use a little of a lot of things) Hi all... I'm looking for an example (or a pointer to one) related to the following. I have a WebService (it works) that fetches data, turns it into XML and returns it to a vb.net client. The "data" though represents property values for an object which the vb.net client has created and now has to load. Just about every...
6
3434
by: Bruce W.1 | last post by:
The intent of my web service is an RSS feed from a blog. Originally I used a StringBuilder to make the XML and returned a string from the webmethod. But this doesn't display properly in IE. So now I'm trying an XmlTextWriter instead. I whipped-up another webservice based on this: http://www.codeproject.com/aspnet/RSSviaXmlTextWriter.asp?print=true This example isn't set up strictly as a webservice. It seems to output to an aspx...
20
3185
by: Razzie | last post by:
Hey all, I'm really going through a small hell right now - I've completely lost it :) I made a project, using two interop libraries from exchange (created them as in this msdn article: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnsmtps/html/writingmngsinks.asp). I set my project properties as 'Register as COM interop' to true, I can install it my project on my developement machine without a flaw. Great.
10
19134
by: Mark Jerde | last post by:
I'm trying to learn the very basics of using an unmanaged C++ DLL from C#. This morning I thought I was getting somewhere, successfully getting back the correct answers to a C++ " int SumArray(int ray, int count)" Now I'm having problems with C++ "return(false)" being True in C#. Here is the C# code. ========================= using System; using System.Runtime.InteropServices; //
9
3208
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. What it does is to call a webservice with two parameters, one being a integer, the other one being a "String" which contains XML (not the best practice, however that is the target interface and we cannot change that).
1
2857
by: louis_la_brocante | last post by:
Dear all, I am having trouble generating a client proxy for a webservice whose methods return a "complex" type. The type is complex in that it is a class whose members are a mix of primitive types and of more elaborate classes implementing IXmlSerializable. The resulting WSDL file for the webservice has two separate schemas in its <types> sections, and the client proxy (generated with wsdl.exe) is missing the definitions of the...
1
3257
by: Bart Roozendaal | last post by:
Hi, I have setup a (my first) C# assembly. I am using the COM Interop services to use the assembly from a Delphi program. Is there a way to return a XmlDomDocument object from the assembly to the Delphi program? If I try to return the XmlDocument object itself, I get an error like: This type has a ComVisible(false) parent in its hierarchy.
1
2749
by: v4u2chat | last post by:
Do I need to extend any of classes from AXIS to return multiple values? I'm exposing the following method as web service through AXIS to return multiple values. public ContactAddress testService() { ContactAddress cAddr = new ContactAddress(); cAddr.setAddresses1("AAAAAAAAAAAAA"); cAddr.setAddresses2("BBBBBBBBBBBBB"); cAddr.setAddresses3("CCCCCCCCCCCCC");
1
1816
by: fretIT | last post by:
Hello, when I write web method using C# in Visual basic 2005, I can't return the string value to the client request. I got such kind of error Not all code paths return a value. Don't know how to cope that problem. My code is as follow. Thanks in advance
0
8290
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
8815
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8482
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
7306
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
6161
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
5622
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();...
1
2714
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
1
1916
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1593
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.