Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / .NET Framework / Interop / October 2003

Tip: Looking for answers? Try searching our database.

Can C function return pointer-to-structure to C#?

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
John - 08 Oct 2003 17:46 GMT
Hi,

I have a C function that allocates some memory:

struct typedef
{
 double *data;
} mytype;

mytype *init(int size)
{
 mytype *p_mytype = malloc(sizeof(mytype));
 p_mytype->data = malloc(sizeof(double) * size);

 return p_mytype;
}

I don't know how to make it so I can read and write values to the data
pointer that is in mytype from my C# application?

I tried to declare the structure in C# with
StructLayout(LayoutKind.Sequential), but I get:

Method's type signature is not PInvoke compatible

Thanks!
John
Mattias Sj?gren - 08 Oct 2003 23:39 GMT
[DllImport(...)]
static extern unsafe mytype* init(int size);

should work in C#. If you don't want unsafe code, you can also do

[DllImport(...)]
static extern IntPtr init(int size);

and then dereference the IntPtr with Marshal.PtrToStructure.

Just remember that you must provide a function to free the memory
allocated by the library as well.

Mattias

Signature

Mattias Sjögren [MVP]  mattias @ mvps.org
http://www.msjogren.net/dotnet/
Please reply only to the newsgroup.

Ying-Shen Yu[MSFT] - 09 Oct 2003 07:42 GMT
Hi John,
I aggree with our MVP, and here is a simple example:
If you still have problem on this issue, please let me know.
Thanks for using MSDN Newsgroup!
<code unmanaged part>
typedef struct _mytype
{
    int *data;
}mytype;
extern "C" __declspec(dllexport)
mytype* init(int size)
{
 mytype *p_mytype = new mytype();
 p_mytype->data = new int[size];
 for(int i = 0; i < size;i++)
 {
     p_mytype->data[i] = i;
 }
 return p_mytype;
}
</code unmanaged part>
<code>
using System;
using System.Runtime.InteropServices;

namespace Interop_CS
{
    /// <summary>
    /// Summary description for Class1.
    /// </summary>
    class Class1
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {   
            int size = 10;
            IntPtr p = init(size);
            MyType t = Marshal.PtrToStructure(p,typeof(MyType)) as MyType;
            int[] s = new int[size];
            Marshal.Copy(t.data,s,0,size);

            //read from the data
            for(int i = 0; i < size; i++)
            {
                Console.WriteLine(s[i]);
            }
            //change the s
            //write it back to t.data
            Marshal.Copy(s,0,t.data,size);

            //you should provide an corresponding function do free the memory.
            //free_mytype();
        }
        /*
            typedef struct _mytype
            {
                int *data;
            }mytype;
        */
        [StructLayout(LayoutKind.Sequential)]
        public class MyType
        {
            //because you allocated memory in your unmanaged code, we can't marshal
it to array.
            //or the address will lost, and the memory will not be freed.
            public IntPtr data;
        }
        [DllImport("Interop_DLL_Stub.dll")]
        public extern static IntPtr init(int size);
    }
}
</code>

Best regards,

Ying-Shen Yu [MSFT]
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security

This posting is provided "AS IS" with no warranties and confers no rights.
You should not reply this mail directly, "Online" should be removed before
sending, Thanks!

--------------------
| From: Mattias Sj?gren <mattias.dont.want.spam@mvps.org>
| Subject: Re: Can C function return pointer-to-structure to C#?
[quoted text clipped - 26 lines]
|
| Mattias

Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.