Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3793086
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 19, 20262026-05-19T12:43:17+00:00 2026-05-19T12:43:17+00:00

The definition of the exported function in c++ DLL is int func1(const char* input,char**

  • 0

The definition of the exported function in c++ DLL is

int func1(const char* input,char** output)
{
 int returnCode = 0;

 std::stringstream xmlInputStream;
 xmlInputStream<< std::string(input);
 std::stringstream xmlOutputStream;
 returnCode = doRequest(xmlInputStream,xmlOutputStream);
 std::string xmlOutputString =xmlOutputStream.str();
 *output=const_cast<char *> (xmlOutputString.c_str());

cout<<xmlOutputString;

 return returnCode ;
}

I tried to import the function from c# like this…

==================================================================

[DllImport("sample.dll")]
    public static extern int func1(String str1,out String str2);


string str1="hello";
string str2=String.Empty;

MyClass.func1(str1,out str2);
Console.writeln(str2);

====================================================================

Output is garbage value…

Why is it so and how to import this function from c#?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-19T12:43:18+00:00Added an answer on May 19, 2026 at 12:43 pm

    Thats simple, try to use custom marshaling (especially if you want to use char** pointers).

    I found that you are no getting “Memory ass dumb” string, because of some improper realization of doRequest(char*,char**), as well as assigning to the result is not properly handled;

    Firstly, if you are allocating memory in unmanaged process and passes it to managed process, you will need declare some mechanism to free unmanaged memory. Managed GC does not know anything about this memory, which will be lost overwize.

    Secondy, you need to allocate memory for the results, and pass them to the unmanaged process, because the original memory locations can be rewritten in any time.

    Lastly, you are getting only the first characted of the input just because you are not allocated memory for the results, effectively passing only a memory pointer to the memory location of the first output character, say &array[0]

    Here is the compete code (MS VC++/MS C#), which fixes all the issues:

    lib.cpp:

    #include "stdafx.h"
    #include "lib.h"
    using namespace std;
    
    int func1(char* input, char** output)
    {
        stringstream xmlInputStream, xmlOutputStream;
    
        xmlInputStream << string(input);    
        int returnCode = doRequest(&xmlInputStream, &xmlOutputStream);
        string xmlOutputString = xmlOutputStream.str();
    
        //*output=const_cast<char *> (xmlOutputString.c_str());
        long length = sizeof(char) * xmlOutputString.length();
        char* src = const_cast<char *>(xmlOutputString.c_str());
        char* dst = (char*)malloc(length+1);
        memcpy_s(dst, length, src, length);
        dst[length]=0; // 0 byte always ends up given ANSI string
        *output = dst;
    
        //cout << xmlOutputString;
        return returnCode;
    }
    
    int func1_cleanup(char* memptr)
    {
        free(memptr);
        return 0;
    }
    
    
    int doRequest(stringstream* xmlInputStream, stringstream* xmlOutputStream)
    {
        *xmlOutputStream << "Memory ass dumb";
        return 0;
    }
    

    Program.cs:

    using System;
    using System.Runtime.InteropServices;
    namespace test
    {
        class Program
        {
            [DllImport("lib.dll", EntryPoint = "func1", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
            public static extern unsafe int func1(char* input, char** data);
    
            [DllImport("lib.dll", EntryPoint = "func1_cleanup", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
            public static extern unsafe int func1_cleanup(char* data);
    
            static void Main(string[] args)
            {
                string input = "Hello, World!";
                string output;
                int result = func1(input, out output);
            }
    
            private const int S_OK = 0;
    
            public static int func1(string input, out string output)
            {
                unsafe
                {
                    output = null;
                    int result = -1;
                    fixed (char* parray1 = &input.ToCharArray()[0])
                    {
                        //
                        // if you allocating memory in a managed process, you can use this
                        //
                        //char[] array = new char[0xffffff];
                        //fixed(char* parray = &array[0])
                        {
                            //
                            // if you allocating memory in unmanaged process do not forget to cleanup the prevously allocated resources
                            //
                            char* array = (char*)0; 
                            char** parray2 = &array;
                            result = func1(parray1, parray2);
                            if (result == S_OK)
                            {
                                //
                                // if your C++ code returns the ANSI string, you can skip this extraction code block (it can be useful in Unicode, UTF-8, UTF-7, UTF-32, all C# supported encodings)
                                //
                                //byte* self = (byte*)*((int*)parray2);
                                //byte* ptr = self;
                                //List<byte> bytes = new List<byte>();
                                //do
                                //{
                                //    bytes.Add(*ptr++);
                                //}
                                //while (*ptr != (byte)0);
                                //output = Encoding.ASCII.GetString(bytes.ToArray());
                                output = Marshal.PtrToStringAnsi(new IntPtr(*parray2));
                            }
                            func1_cleanup(array);
                        }
                    }
                    return result;
                }
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Created basic C++ DLL and exported names using Module Definition file (MyDLL.def). After compilation
I'm trying to call from C# a function in a custom DLL written in
I have two WIN32 DLL projects in the solution, main.dll should call a function
Splint gives me the following warning: encrypt.c:4:8: Function exported but not used outside encrypt:
On a program of me, the splint checker warns: expat-test.c:23:1: Function exported but not
Module-definition (.def) files provide the linker with information about exports, attributes, and other information
Okay, this one is the reverse of the last question I struggled with... I
I am tryint to integrate CUDA in an existing project, in which several libs
This is my 3rd thread concerning a blowfish problem in C#.Despite the fact I
These days, I use Flex & Bison generated some codes to develop a SQL-parser

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.