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

  • SEARCH
  • Home
  • 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 7629453
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T05:50:20+00:00 2026-05-31T05:50:20+00:00

I’m using DllImport to call the functions of C++ from C#. #if defined(__cplusplus) extern

  • 0

I’m using DllImport to call the functions of C++ from C#.

#if defined(__cplusplus)
extern "C" {
#endif

__declspec(dllexport) int __stdcall ABC(int i);

__declspec(dllexport) char* __stdcall C(int i);

#if defined(__cplusplus)
}
#endif

int __stdcall ABC(int i)

{
    return i;
}

char* __stdcall C(int i)
{
    char* n = new char[i];
    memset(n, 9, i);
    return n;
}

Code in C# is:

using System.Runtime.InteropServices;
using System;

namespace DepartmentStore
{
    class Exercise
    {
        [DllImport("library.dll")]
        public static extern int ABC(int i);

        [DllImport("library.dll")]
        public static extern char* C(int i);

        static int Main()
        {
            int k = ABC(10);
            byte[] b = C(1024);

            return 0;
        }
    }
}

The function ABC(int i) is OK, but the function C(int i) yielded the following error when building:

“Pointers and fixed size buffers may only be used in an unsafe context”

I guess that I didn’t understand how to export a pointer return of functions.

May Someone please tell me the correct way C# invokes functions with the return type as a pointer?

  • 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-31T05:50:22+00:00Added an answer on May 31, 2026 at 5:50 am

    The P/Invoke later doesn’t know how to marshal C-style arrays from the unmanaged to the managed side; unlike SAFEARRAY, there is no information embedded in C-style arrays that the P/Invoke later can use to determine how many bytes should be copied.

    Because of this, you’ll want to declare your C function to return an IntPtr and then call the Marshal.PtrToStrAnsi method to convert the pointer to a string on the managed side like so:

    [DllImport("library.dll")]
    public static extern IntPtr C(int i);
    
    static int Main()
    {
        int k = ABC(10);
        IntPtr b = C(1024);
    
        string s = Marshal.PtrToStrAnsi(b);
    
        // Problem: How do you release what is pointed to
        // by IntPtr?
    
        return 0;
    }
    

    Additionally, you’ll have to pass the IntPtr back to the unmanaged side to deallocate the memory that you allocated with new; if you don’t you’ll have a memory leak.

    An easier option is to create a managed wrapper for your unmanaged library in C++ that exposes managed functions which make the calls and perform the conversion to a String^ (using marshal_as) like so:

    // compile with: /clr
    #include <stdlib.h>
    #include <string.h>
    #include <memory>
    #include <msclr\marshal.h>
    
    using namespace System;
    using namespace msclr::interop;
    
    String^ WrappedC(int i) {
       // Make the call to the native function.
       // Let's store in an auto_ptr to handle
       // cleanup when the wrapper is exited.
       auto_ptr<char> c(C(i));
    
       // Convert to a managed string and
       // return.
       return marshal_as<String^>(c.get());
    }
    

    If you didn’t want to marshal back a string, and instead marshal back a byte array, then I’d still recommend the wrapper approach (although in this case, it requires you to have some specific knowledge in order to create the managed array to return):

    // compile with: /clr
    #include <stdlib.h>
    #include <memory>
    
    using namespace System;
    using namespace msclr::interop;
    
    String^ WrappedC(int i) {
       // Make the call to the native function.
       // Let's store in an auto_ptr to handle
       // cleanup when the wrapper is exited.
       auto_ptr<char> c(C(i));
    
       // Copy the pointer.
       char* p = c.get();
    
       // The byte array to return.
       // i is the size of the array, as per the call
       // to C.
       array<byte>^ a = gcnew array<byte>(i); 
    
       // Populate.
       for (int index = 0; index < i; ++index) 
           a[index] = (byte) *p++; 
    
       // Return the array.
       return a;
    }
    

    These are better options than handling it in managed code completely, as you don’t have to worry about continuously marshalling between managed and unmanaged to handle pointers to memory allocated in the unmanaged space.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
That's pretty much it. I'm using Nokogiri to scrape a web page what has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
For some reason, after submitting a string like this Jack’s Spindle from a text
I am reading a book about Javascript and jQuery and using one of the
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
We're building an app, our first using Rails 3, and we're having to build
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
We are using XSLT to translate a RIXML file to XML. Our RIXML contains

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.