Measurement Studio for .NET Languages

cancel
Showing results for 
Search instead for 
Did you mean: 

Returning ViChar[] from VC++ to VB

I'm experimenting in VC.NET, as several may have noticed.

I have some strings in VC++ of type ViChar[255]. How can I return these to
VB in a form that VB sees as a string, which I assume is a pointer to a
System::String object created within my C code?

My present solution is highly inelegant, using memcpy to copy the bytes from
the address of the ViChar string to a char array that can then be returned.
VB then sees it as an SByte array and I have to loop through the array to
rebuild the original string.

I have been unable to declare a function parameter as ViChar[] since I get
into the circular loop;

error C2697: 'test' : must explicitly specify __gc or __nogc for an array
declared in a managed type

or

error
C3150: 'test' : '__gc' can only be applied to a class, struct,
interface, array or pointer

depending on whether I put the __gc there or not.

--
Dr. Craig Graham, Software Engineer
Advanced Analysis and Integration Limited, UK. http://www.aail.co.uk/
0 Kudos
Message 1 of 3
(4,198 Views)
You can convert a ViChar array to a .NET string via either a.) the .NET string constructor or b.) System.Runtime.InteropServices.Marshal.PtrToStringAnsi. For example, here is a managed C++ class that provides methods that demonstrate both of these methods:

#pragma once
#include "C:\VXIpnp\WinNT\include\visatype.h"

using namespace System;
using namespace System::Runtime::InteropServices;

namespace ViCharTest
{
public __gc class Test
{
public:
Test()
{
}

System::String* GetStringViaConstructor()
{
ViChar* value = "Test";
return new String(value);
}

System::String* GetStringViaMarshal()
{
ViChar* value = "Test";

return Marshal::PtrToStringAnsi(IntPtr(value));
}
};
}

You can then test these from a VB.NET client like this:

Dim test As ViCharTest.Test = New ViCharTest.Test
MsgBox(test.GetStringViaConstructor())
MsgBox(test.GetStringViaMarshal())

I believe that either of these approaches will do what you want. Please give this a try and reply to let us know how it worked out. Thanks.

- Elton
Message 2 of 3
(4,198 Views)
"Elton Wells" wrote in message
news:5065000000050000001A120100-1042324653000@exchange.ni.com...
> You can convert a ViChar array to a .NET string via either a.) the
> NET string constructor or b.)
> System.Runtime.InteropServices.Marshal.PtrToStringAnsi. For example,
> here is a managed C++ class that provides methods that demonstrate
> both of these methods:

Ooo, very nice. Thanks.

--
Dr. Craig Graham, Software Engineer
Advanced Analysis and Integration Limited, UK. http://www.aail.co.uk/
0 Kudos
Message 3 of 3
(4,198 Views)