.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links


Posted By:      Posted Date: August 29, 2010    Points: 0   Category :.NET Framework
hi all i have problem of using Marshal functions, i have the following .h declarations : typedef struct CPS_InfosCarte { UINT8 IdEmetteur [11]; UINT8 IdCarteLog [10]; UINT8 CategorieCarte [2]; UINT8 DateEmis [8]; UINT8 DateFinVal [8]; } CPS_InfosCarte ; UINT16 API_ENTRY CPS_InformationsCarte( UINT16 NumSession, struct CPS_InfosCarte PTR pIC, struct CPS_StatusService PTR pStatusService, PUINT16 pEtatCarte); That i had declared in vb.net as :   <StructLayout(LayoutKind.Sequential, Pack:=4)> _ Private Structure CPS_InfosCarte <MarshalAs(UnmanagedType.ByValArray, sizeconst:=11)> Dim IdEmetteur() As Byte <MarshalAs(UnmanagedType.ByValArray, sizeconst:=10)> Dim IdCarteLog() As Byte <MarshalAs(UnmanagedType.ByValArray, sizeconst:=2)> Dim CategorieCarte() As Byte <MarshalAs(UnmanagedType.ByValArray, sizeconst:=8)> Dim DateEmis() As Byte <MarshalAs(UnmanagedType.ByValArray, sizeconst:=8)> Dim DateFinVal() As Byte End Structure <DllImport("K:\cpsw32.dll" , EntryPoint:="CPS_InformationsCarte" , SetLastError:=True )> _ Private Shared Function CPS_InformationsCarte(ByVal NumSession As UInt16, B

View Complete Post

More Related Resource Links

Can I marshal the same object to two URIs?

Due to external constraints, I have to provide remoting access to the same Singleton object through two URI's. Omitting all the remoting configuration (which does seem to set up correctly), the general idea is: m_RemotedComponent = new RemotedComponent(); RemotingServices.Marshal(m_RemotedComponent, remotingName1); RemotingServices.Marshal(m_RemotedComponent, remotingName2); The two connections provide different interfaces that the one component supports and are accessed by different clients. Regardless of the order in which the two Marshal statements appear, the first one works and the second one doesn't. Upon attempting to connect to the second URI (regardless of whether I have an active connection to the first URI) using Activator.GetObject(...), I get the error message saying that the object has to derive from MarshalByRefObject. But, since I can always instantiate the first-listed URI successfully, it obviously does derive from that. If I create a second RemotedComponent, I can marshal it successfully to the second URI, so the problem is clearly related to trying to marshal the same object to two URI's. Is this supposed to be possible? If so, how?

Marshal C++ Struct to C# class?

Is it possible to have the Marshaller move a C++ struct to a C# class? I defined the C# class with StructLayout Explicit, and mapped it. It works perfectly as a struct, but if I change to class, I get a buffer overflow. Is there some way to work around this? I need to add methods to these "classes", and making a wrapper class that has all the same fields seems like such a waste.

Problems with Marshal.GetActiveObject

I think I'm having problems with this: private static object scComm = Marshal.GetActiveObject("ScComm32.Document"); This call returns but the returned object completely devoid of anything useful, compared to when I do something like this: private static object myWord = Marshal.GetActiveObject("Word.Application"); I have an old VB6 app that doesn't seem to have a problem doing this with one little call to GetObject. Any help appreciated. Thanks.

Marshal of C++ char[] to C# string

Hi guys, this is my problem. I have some C++ structure in unmanaged DLL. I need to use those structures in C#, in managed code.It seems all simple.... This is the C++ code of structures. Be careful to the structure "T__KRON_Struct_Error_Context" that is the structure that causes problems. ****************************  typedef char                    T__Char; typedef unsigned __int32        T__UInt32;  typedef enum {  KRON_ERR_SUCCESS       =1000,   KRON_ERR_RQC_DUPLICATED      =1601,  KRON_ERR_RQC_BAD_CONF_FILE     =1700, }T__KRON_Returned_Codes;  typedef struct {  T__KRON_Returned_Codes m__errorcode;  T__Char     m__errormessage[150];  T__Char     m__errorfile[256];  T__UInt32    m__errorline; }T__KRON_Struct_Error_Context; ***************************** My marshaling of structures in the C# Wrapper is the following:     [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, CharSet = System.Runtime.InteropServices.CharSet.Ansi)]    public struct T__KRON_Struct_Error_Context    {        public T__KRON_Returned_Codes m__errorcode;        /// T__Char[150]        [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst = 150)]        public string m__errormessage;        /// T__Char[256]        [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.

HowTo Marshal C++ enums and copy buffer of unsigned 16bit integer


Hi together,

I'm trying to wrap an API of a digital camera SDK (unmanaged C++). Some of the functions a working, but some of them ... :(

1. HowTo marshal  C++  enums?

This is a part of the api.h file:



	DCAM_DATATYPE_UINT8	=	0x00000001,	/* bit 0 */
	DCAM_DATATYPE_UINT16	=	0x00000002,	/* bit 1 */
	DCAM_DATATYPE_UINT32	=	0x00000008,	/* bit 3 */
	DCAM_DATATYPE_MOSAIC8	=	0x00010000,	/* bit 16, 8bit mosaic */
	DCAM_DATATYPE_MOSAIC16	=	0x00020000,	/* bit 17, 16bit mosaic */
	DCAM_DATATYPE_RGB24	=	0x00040000,	/* bit 18, 8bit*3, [ r0, g0, b0], [r1, g1, b1] */
	DCAM_DATATYPE_RGB48	=	0x00100000,	/* bit 20, 16bit*3, [ r0, g0, b0], [r1, g1, b1] */


BOOL DCAMAPI dcam_getdatatype			( HDCAM h, DCAM_DATATYPE* pType );
BOOL DCAMAPI dcam_setdatatype			( HDCAM h, DCAM_DATATYPE type );<br/>


And this is what I wrote in C#:

Marshal Nested Stucture using PInvoke



I am using C# in a VisualStudio 2008 environment and
have to retrieve data from a 3rd party DLL written in C.
I can access all but two of the C functions successfully.
Both of these functions require a nested structure
to be passed, so the structure can be populated with data.

// supplied C structure
typedef  struct
   float  fPeak;
   float  fMean;
   float  fStd; 
   int    iNoPeaks;
    float  fArea;
    float  fPeak;
    float  fMean;
    float  fStd; 
    int    iNoSubpeaks;
      float  fArea;   
      float  fPeak;   
      float  fMean;   
      float  fStd;    
typedef  pcs_distr_info *  p_pcs_distr_info;
// supplied C prototype
int Analysis(
  pcs_handle hPcsObject        // handle
  p_pcs_distr_info  pPeaksInfo // problem with this line

// part of, example C code supplied
pcs_distr_info  DistrInfo;
int result = Analysis( hPcsObject, &DistrInfo );
//C# attempt at retrieving data from the DLL function

 public static extern int Analysis(System.IntPtr handle, 
                                   out DistrInfo distributionInfo);

// structure in C#
public const int PCS_MAX_NO_PEAKS     = 20;
public const int

COM Interop, Marshal C# IEnumerator->Native C++ IEnumVARIANT?


Hi folks,

I have a C# Windows Service which hosts a COM class whose client is C++ native code. On one method of the interface, there is the potential for a lot of data to be returned. Internally, the method is using an ArrayList of structs. The method has an [out] parameter typed as IEnumerator. In the method, I assign ArrayList.GetEnumerator() to this out parameter. The Type library export is getting it right; it is typing the out parameter as IEnumVARIANT, as expected.

However, on the client side, when I try to call Next() on the IEnumVARIANT interface pointer, I get an E_INVALIDARG HRESULT. Since the arguments to Next() are of the correct types, I'm at a loss as to what the problem is, and am thinking I'm doing something wrong on the Host side. Can anyone help me out here?

Many thanks!

Regards, D. T. Doutel

Marshal a number of strings in struct


Hi, I confuse with marshaling strings in struct. I want output many strings in C++ Dll once a time to C# code. But it always has some problems.

I tried to use this way:


 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
    public struct DcmRecord
      public String PatientsBirthDate;
      public String PatientsSex;
      public String PatientsName;
      public String PatientID;
      public String PatientsBirthTime;
      public String OtherPatientIDs;
      public String OtherPatientNames;
      public String EthnicGroup;
      public String NumberofPatientRelatedStudies;
      public String NumberofPatientRelatedSeries;
      public String NumberofPatientRelatedInstances;

    [return: MarshalAs(UnmanagedType.I1)]

How to marshal safearray arguments when calling managed C# method from unmanaged C++?


I'm trying to utilize an old application framework from managed C# code but I don't understand how to marshal the safearray argument which is forwarded to the managed code. Here is a code snipped describing how the managed code is called:

  try {
    _ObjectHandlePtr pObjectHandle; 
    _ObjectPtr pObject; 
    _TypePtr pType;
    SAFEARRAY* psa;

    // Create an instance of a type from an assembly
    pObjectHandle = pDefaultDomain->CreateInstanceFrom(L"ClassLibrary1.dll",   // no path -- local directory
    variant_t vtobj = pObjectHandle->Unwrap();                   // Get an _Object (as variant) from the _ObjectHandle
    vtobj.pdispVal->QueryInterface(__uuidof(_Object),(void**)&pObject); // QI the variant for the Object iface
    pType = pObject->GetType();                             // Get the _Type iface
    psa = SafeArrayCreateVector(VT_VARIANT,0,1);               // Create 

Read data with Marshal.Copy



Is it possible to read part of data with Marshal.Copy?

I am using Marshal.Copy in my code the following way,

Marshal.Copy(ptrData, dest, startIndex, size); // dest array is a 'byte' array

Suppose, ptrData holds  a data of length 100. And I want to read data starting from 10th location with length of data is 5.


I don't think I can do this Marshal.Copy as none of the parameters in this function accepts 'StartIndex' in source.


The parameters in Marshal.Copy are:

  The memory pointer to copy from.

  The array to copy to.

  The zero-based index into the array where Copy should start.

  The number of array elements to copy.

So, is there any way we can copy the range of data from source pointer.



Marshal a C# struct to native C++


Platform is WS 2008 RC2, VS 2010.

I have what I think should be a pretty straightforward marshalling situation, but it just isn't working as expected.

Native Code:

#pragma pack(push, 8)
struct Handle
unsigned long Type;
void* Value;
void* Owner;
#pragma pack(pop)

__declspec(dllexport) Handle __cdecl CreateStyleProvider(const wchar_t* provider);
__declspec(dllexport) Handle __cdecl CreateOutputGroup(long ordinal, Handle style);

The Handle struct is really just opaque data that gets passed around.

C# code:

[StructLayout(LayoutKind.Sequential, Pack=8)]

using C DLL in C# code : error - Cannot marshal 'parameter #2': Internal limitation: structure is


I have to use a dll written in C in a C# VS project.

I have some difficulties to translate and use the structures declared in C.

structure of the trend list :

C structure

 typedef struct
    WV_PARAMETER_ID    WvParameterID [WV_MAX_TREND_PARAMETERS];                  ;
    int                NumberOfTrends;



The problem I have is that there is only one returned value for the "NumberOfTrends" but 60 for the others. Then I found that I need to create the structures as follow.

This is working.

C# Structure

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
        public struct WV_TREND_LIST

ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend