How to convert class instance to IntPtr

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ramanujam kv
    New Member
    • Dec 2010
    • 2

    How to convert class instance to IntPtr

    I have two C# classes (Interop & Assembly)which is shown below

    Code:
    public class CTest
    {
       public CTest()
       {
       }
    
       public void SimpleFunction()
       {
       }
    }
    
    public class CGetSimpleFunctionTest
    {
       public CGetSimpleFunctionTest()
       {
       }
    
       public IntPtr GetSimpleFunctionClass()
       {
           CTest test = new CTest();
    
           IntPtr pTest = new IntPtr();
           GCHandle gch = GCHandle.Alloc(test, GCHandleType.Pinned);
       }
    }
    I have a unmanged c++ client and c++ client creates an instance of CGetSimpleFunct ionTest through COM. it calls GetSimpleFuncti onClass()to get the CTest object. Then it calls SimpleFunction( ) on CTest object.


    Problem is when GetSimpleFuncti onClass() is called, GCHandle.Alloc is throwing an exception "Object contains non-primitive or non-blittable data." . I don't have any data members in CTest class just one function SimpleFunction( ).


    I searched entire net to solve the above problem, but i could not get any solution.

    Please Please can anyone helpme to solve this problem
  • Plater
    Recognized Expert Expert
    • Apr 2007
    • 7872

    #2
    Have you tried working with Marshal.Structu reToPtr()?

    EDIT: Ok it produces the same message pretty much.
    For Marshal.SizeOf( ) I see this:
    "You can only use Marshal.SizeOf to get the size of a value type (struct) or
    a class that has an explicit layout declaration (StructLayoutAt tribute)"

    I recomend using: [StructLayoutAtt ribute(LayoutKi nd.Sequential, Pack = 1)]
    That will allow marshalling of your class, and pack=1 means it will allign the data bytes on single byte offsets (my default seems to be 4 bytes)
    Last edited by Plater; Dec 14 '10, 03:19 PM.

    Comment

    Working...