Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Pointers in c#

Tags:

c#

pointers

I have a windows form application in c#, that uses a function in c++. This was done using a c++ wrapper. However, the function requires the use of pointers and c# does not allow the use of pointers with string arrays. What can be done to overcome this? I have read up on using marshal but i am not sure if this is suitable for this case and if so how should it be integrated with my code. The following is the C# code:

 int elements = 10;
string [] sentence = new string[elements];

unsafe
{
    fixed (string* psentence = &sentence[0])
    {
        CWrap.CWrap_Class1 contCp = new CWrap.CWrap_Class1(psentence, elements);
        contCp.getsum();
    }
}

c++ function declaration: funct::funct(string* sentence_array, int sentence_arraysize)

c++ wrapper: CWrap::CWrap_Class1::CWrap_Class1(string *sentence_array, int sentence_arraysize) { pcc = new funct(sentence_array, sentence_arraysize); }

like image 346
user2990515 Avatar asked Nov 14 '13 04:11

user2990515


1 Answers

If I understand you correctly you want to call a C function with string as parameters.
For this, you usually use PInvoke (platform invoke), which uses marshalling under the hand.

This example takes a string and returns a string.

[DllImport(KMGIO_IMPORT,CallingConvention=CallingConvention.Cdecl)]     
//DLL_EXPORT ushort CALLCONV cFunction(char* sendString, char* rcvString, ushort rcvLen);
private static extern UInt16 cFunction(string sendString, StringBuilder rcvString, UInt16 rcvLen);

public static string function(string sendString){
    UInt16  bufSize = 5000;
    StringBuilder retBuffer = new StringBuilder(bufSize);
    cFunction(sendString, retBuffer, bufSize);
    return retBuffer.ToString();
}
like image 187
joe Avatar answered Oct 20 '22 06:10

joe