2

I am calling unmanaged C programming code from C# .Net managed code. But I am unable to pass string array as a parameter to function from .Net Function in C:

dllmain(const int argc, const char *argv[]){}

Please help me, how I can call this function from C Sharp.Net

Thanks.

2 Answers 2

1

Here is a way you can do that:

C# code:

  1. Declare C function you want call from C#

    [DllImport("<DLL_File_Name>.dll", CharSet = CharSet.Auto, EntryPoint = "dllmain", ExactSpelling = false, CallingConvention = CallingConvention.StdCall)]
    public static extern void dllmain(ref string str1);
    
  2. Define the string

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 100)]
        public string str1;
    
  3. Call the C function from C# code

        dllmain(ref str1);
    

C Code:

  1. Function prototype

    __declspec(dllexport) void __stdcall dllmain(char *str1);
    
  2. Function definition

    void__stdcall dllmain(char *str1)
    {
        :
    }
    

Hope this will be helpful for you. :-)

Sign up to request clarification or add additional context in comments.

1 Comment

the question was regarding a string array, not just one string
1

Add the following attributes to the parameter argv when declaring the function in .net:

[In][MarshalAsAttribute(UnmanagedType.LPArray, ArraySubType=UnmanagedType.LPStr)]

You should also add the CharSet=CharSet.Unicode property to the DllImport attribute applied to the external function.

1 Comment

Hi, Your way of connecting unmanaged code with managed code is working fine but when I am passing arguments by ref string, then it's not working. Data is changed automatically in the arguments. Please help me. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.