Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to pass byte array parameter from C# to C++

Status
Not open for further replies.

juhaka

Programmer
Nov 14, 2002
26
FI
Hi!

Now I have a need to pass byte array (byte[]) parameter from C# component to C++ component (and vice versa). So, I have an old C++ component, which have a function like unsigned char* encode(unsigned char* arrBytes). I thought, that I will do a wrapper class for it, but how...

JuhaKa
 
Hi!

I found one solution for this problem by myself...I'm not sure is it the rigth (and only) one....

This is an example...please send yuor comments, if here is fatal errors.

The wrapper class
The header.

// StringConverter.h

#pragma once
#include "Converter.h"
using namespace System;

namespace StringConverter
{
public __gc class StrConverter: public IDisposable
{
private:
Converter *conv;
public:
StrConverter();
~StrConverter();
System::Byte ToLower(System::Byte str __gc[])[];
void Dispose(bool disposing);
void Dispose();

};
}



The cpp code.

// This is the main DLL file.

#include "stdafx.h"
#include <stdio.h>
#include "string.h"
#include "Converter.h"

#include "StringConverter.h"

using namespace System::Runtime::InteropServices;

StringConverter::StrConverter::StrConverter()
{
conv = new Converter();
}

StringConverter::StrConverter::~StrConverter()
{
printf("\nDestructor...");
this->Dispose(false);

}

void StringConverter::StrConverter::Dispose()
{
printf("\nDispose()....");
this->Dispose(true);
}

void StringConverter::StrConverter::Dispose(bool disposing)
{
printf("\nDispose(bool disposing)...");
if(this->conv != NULL)
{
delete conv;
conv = NULL;
}
if(disposing == true)
{
GC::SuppressFinalize(this);
}
}


System::Byte StringConverter::StrConverter::ToLower(System::Byte str __gc[])[]
{
unsigned char* buff = new unsigned char[str->Length + 1];

//copying byte array to the pointer...
Marshal::Copy(str, 0, buff, str->Length);
printf("buff: %s", buff);
unsigned char* ts = buff;
for(int i = 0; i < str->Length; i++)
{
ts++;
}
*ts = NULL;
printf("\nbuff: %s", buff);
int len = 0;

//calling original C++ function !!!
unsigned char* tmp = this->conv->toLower(buff, &len);

//Copying returned value to new byte array
System::Byte retBytes __gc[] = new System::Byte __gc[len - 1];
Marshal::Copy(tmp, retBytes, 0, retBytes->Length);

//free memory...
delete [] buff;
buff = NULL;
delete [] tmp;
tmp = NULL;
return retBytes;
}



Juha Ka
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top