Search Results

Search found 141 results on 6 pages for 'marshalling'.

Page 1/6 | 1 2 3 4 5 6  | Next Page >

  • Marshalling to a native library in C#

    - by Daniel Baulig
    I'm having trouble calling functions of a native library from within managed C# code. I am developing for the 3.5 compact framework (Windows Mobile 6.x) just in case this would make any difference. I am working with the waveIn* functions from coredll.dll (these are in winmm.dll in regular Windows I believe). This is what I came up with: // namespace winmm; class winmm [StructLayout(LayoutKind.Sequential)] public struct WAVEFORMAT { public ushort wFormatTag; public ushort nChannels; public uint nSamplesPerSec; public uint nAvgBytesPerSec; public ushort nBlockAlign; public ushort wBitsPerSample; public ushort cbSize; } [StructLayout(LayoutKind.Sequential)] public struct WAVEHDR { public IntPtr lpData; public uint dwBufferLength; public uint dwBytesRecorded; public IntPtr dwUser; public uint dwFlags; public uint dwLoops; public IntPtr lpNext; public IntPtr reserved; } public delegate void AudioRecordingDelegate(IntPtr deviceHandle, uint message, IntPtr instance, ref WAVEHDR wavehdr, IntPtr reserved2); [DllImport("coredll.dll")] public static extern int waveInAddBuffer(IntPtr hWaveIn, ref WAVEHDR lpWaveHdr, uint cWaveHdrSize); [DllImport("coredll.dll")] public static extern int waveInPrepareHeader(IntPtr hWaveIn, ref WAVEHDR lpWaveHdr, uint Size); [DllImport("coredll.dll")] public static extern int waveInStart(IntPtr hWaveIn); // some other class private WinMM.WinMM.AudioRecordingDelegate waveIn; private IntPtr handle; private uint bufferLength; private void setupBuffer() { byte[] buffer = new byte[bufferLength]; GCHandle bufferPin = GCHandle.Alloc(buffer, GCHandleType.Pinned); WinMM.WinMM.WAVEHDR hdr = new WinMM.WinMM.WAVEHDR(); hdr.lpData = bufferPin.AddrOfPinnedObject(); hdr.dwBufferLength = this.bufferLength; hdr.dwFlags = 0; int i = WinMM.WinMM.waveInPrepareHeader(this.handle, ref hdr, Convert.ToUInt32(Marshal.SizeOf(hdr))); if (i != WinMM.WinMM.MMSYSERR_NOERROR) { this.Text = "Error: waveInPrepare"; return; } i = WinMM.WinMM.waveInAddBuffer(this.handle, ref hdr, Convert.ToUInt32(Marshal.SizeOf(hdr))); if (i != WinMM.WinMM.MMSYSERR_NOERROR) { this.Text = "Error: waveInAddrBuffer"; return; } } private void setupWaveIn() { WinMM.WinMM.WAVEFORMAT format = new WinMM.WinMM.WAVEFORMAT(); format.wFormatTag = WinMM.WinMM.WAVE_FORMAT_PCM; format.nChannels = 1; format.nSamplesPerSec = 8000; format.wBitsPerSample = 8; format.nBlockAlign = Convert.ToUInt16(format.nChannels * format.wBitsPerSample); format.nAvgBytesPerSec = format.nSamplesPerSec * format.nBlockAlign; this.bufferLength = format.nAvgBytesPerSec; format.cbSize = 0; int i = WinMM.WinMM.waveInOpen(out this.handle, WinMM.WinMM.WAVE_MAPPER, ref format, Marshal.GetFunctionPointerForDelegate(waveIn), 0, WinMM.WinMM.CALLBACK_FUNCTION); if (i != WinMM.WinMM.MMSYSERR_NOERROR) { this.Text = "Error: waveInOpen"; return; } setupBuffer(); WinMM.WinMM.waveInStart(this.handle); } I read alot about marshalling the last few days, nevertheless I do not get this code working. When my callback function is called (waveIn) when the buffer is full, the hdr structure passed back in wavehdr is obviously corrupted. Here is an examlpe of how the structure looks like at that point: - wavehdr {WinMM.WinMM.WAVEHDR} WinMM.WinMM.WAVEHDR dwBufferLength 0x19904c00 uint dwBytesRecorded 0x0000fa00 uint dwFlags 0x00000003 uint dwLoops 0x1990f6a4 uint + dwUser 0x00000000 System.IntPtr + lpData 0x00000000 System.IntPtr + lpNext 0x00000000 System.IntPtr + reserved 0x7c07c9a0 System.IntPtr This obiously is not what I expected to get passed. I am clearly concerned about the order of the fields in the view. I do not know if Visual Studio .NET cares about actual memory order when displaying the record in the "local"-view, but they are obviously not displayed in the order I speciefied in the struct. Then theres no data pointer and the bufferLength field is far to high. Interestingly the bytesRecorded field is exactly 64000 - bufferLength and bytesRecorded I'd expect both to be 64000 though. I do not know what exactly is going wrong, maybe someone can help me out on this. I'm an absolute noob to managed code programming and marshalling so please don't be too harsh to me for all the stupid things I've propably done. Oh here's the C code definition for WAVEHDR which I found here, I believe I might have done something wrong in the C# struct definition: /* wave data block header */ typedef struct wavehdr_tag { LPSTR lpData; /* pointer to locked data buffer */ DWORD dwBufferLength; /* length of data buffer */ DWORD dwBytesRecorded; /* used for input only */ DWORD_PTR dwUser; /* for client's use */ DWORD dwFlags; /* assorted flags (see defines) */ DWORD dwLoops; /* loop control counter */ struct wavehdr_tag FAR *lpNext; /* reserved for driver */ DWORD_PTR reserved; /* reserved for driver */ } WAVEHDR, *PWAVEHDR, NEAR *NPWAVEHDR, FAR *LPWAVEHDR; If you are used to work with all those low level tools like pointer-arithmetic, casts, etc starting writing managed code is a pain in the ass. It's like trying to learn how to swim with your hands tied on your back. Some things I tried (to no effect): .NET compact framework does not seem to support the Pack = 2^x directive in [StructLayout]. I tried [StructLayout(LayoutKind.Explicit)] and used 4 bytes and 8 bytes alignment. 4 bytes alignmentgave me the same result as the above code and 8 bytes alignment only made things worse - but that's what I expected. Interestingly if I move the code from setupBuffer into the setupWaveIn and do not declare the GCHandle in the context of the class but in a local context of setupWaveIn the struct returned by the callback function does not seem to be corrupted. I am not sure however why this is the case and how I can use this knowledge to fix my code. I'd really appreciate any good links on marshalling, calling unmanaged code from C#, etc. Then I'd be very happy if someone could point out my mistakes. What am I doing wrong? Why do I not get what I'd expect.

    Read the article

  • Marshalling non-Blittable Structs from C# to C++

    - by Greggo
    I'm in the process of rewriting an overengineered and unmaintainable chunk of my company's library code that interfaces between C# and C++. I've started looking into P/Invoke, but it seems like there's not much in the way of accessible help. We're passing a struct that contains various parameters and settings down to unmanaged codes, so we're defining identical structs. We don't need to change any of those parameters on the C++ side, but we do need to access them after the P/Invoked function has returned. My questions are: What is the best way to pass strings? Some are short (device id's which can be set by us), and some are file paths (which may contain Asian characters) Should I pass an IntPtr to the C# struct or should I just let the Marshaller take care of it by putting the struct type in the function signature? Should I be worried about any non-pointer datatypes like bools or enums (in other, related structs)? We have the treat warnings as errors flag set in C++ so we can't use the Microsoft extension for enums to force a datatype. Is P/Invoke actually the way to go? There was some Microsoft documentation about Implicit P/Invoke that said it was more type-safe and performant. For reference, here is one of the pairs of structs I've written so far: C++ /** Struct used for marshalling Scan parameters from managed to unmanaged code. */ struct ScanParameters { LPSTR deviceID; LPSTR spdClock; LPSTR spdStartTrigger; double spinRpm; double startRadius; double endRadius; double trackSpacing; UINT64 numTracks; UINT32 nominalSampleCount; double gainLimit; double sampleRate; double scanHeight; LPWSTR qmoPath; //includes filename LPWSTR qzpPath; //includes filename }; C# /// <summary> /// Struct used for marshalling scan parameters between managed and unmanaged code. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct ScanParameters { [MarshalAs(UnmanagedType.LPStr)] public string deviceID; [MarshalAs(UnmanagedType.LPStr)] public string spdClock; [MarshalAs(UnmanagedType.LPStr)] public string spdStartTrigger; public Double spinRpm; public Double startRadius; public Double endRadius; public Double trackSpacing; public UInt64 numTracks; public UInt32 nominalSampleCount; public Double gainLimit; public Double sampleRate; public Double scanHeight; [MarshalAs(UnmanagedType.LPWStr)] public string qmoPath; [MarshalAs(UnmanagedType.LPWStr)] public string qzpPath; }

    Read the article

  • jaxb namespaces in each element instead of root element during marshalling

    - by Anton
    By default, jaxb 2 lists all (all possible required) namespaces in root element during marshalling: <rootElement xmlns="default_ns" xmlns:ns1="ns1" xmlns:ns2="ns2"> <ns1:element/> </rootElement> Is there a way to describe namespace in each element instead of root element ?: <rootElement xmlns="default_ns"> <element xmlns="ns1"/> </rootElement> It also solves the problem of "unnecessary namespaces", which is also important in my case. Any suggestions appreciated.

    Read the article

  • SWIG: C++ to C#, pointer to pointer marshalling.

    - by CaRT
    I have some legacy code I want to port to C#. I cannot modify the C++ code, I just have to make do with what I'm given. So, the situation. I'm using SwIG, and I came across this function: void MarshalMe(int iNum, FooClass** ioFooClassArray); If I ran SWIG over this, it wouldn't know what to do with the array, so it will create a SWIGTYPE_p_pFooClass. Fair enough! C# code for this would look like void MarshalMe(int iNum, SWIGTYPE_p_p_FooClass ioFooClassArray); // Not ideal! There are some techniques for marshalling this kind of code correctly, so I tried a few of them: %typemap(ctype) FooClass** "FooClass**" %typemap(cstype) FooClass** "FooClass[]" %typemap(imtype, inattributes="[In, Out, MarshalAs(UnmanagedType.LPArray)]") FooClass** "FooClass[]" %typemap(csin) FooClass** "$csinput" %typemap(in) FooClass** "$1 = $input;" %typemap(freearg) FooClass** "" %typemap(argout) FooClass** "" This effectively creates a nicer signature: void MarshalMe(int iNum, FooClass[] ioFooClassArray); // Looks good! Would it work? However, when I try to run it, I get the following error: {"Exception of type 'System.ExecutionEngineException' was thrown."} Any ideas about the actual typemap?

    Read the article

  • Interface Marshalling in Delphi

    - by cemick
    I want to send Interface Ref of IVApplication from Visio Add-in to my other one COM server. But I have Ole exception. Now i do that: Code in Visio Add-in: var IStrm: IStream; hres: HResult; rhglobal: HGLOBAL; VisioAppl: IVApplication; begin hres := CreateStreamOnHGlobal(0, TRUE, IStrm); if Succeeded(hres) then hres := CoMarshalInterface(IStrm, IID_IVApplication, VisioAppl, MSHCTX_LOCAL, 0, MSHLFLAGS_NORMAL); if (Succeeded(hres)) then begin hres := GetHGlobalFromStream(IStrm, rhglobal); IStrm := nil; end; end; After this I create instance of my COM server and pass rhglobal to him. Code of my COM server: procedure (AHGlobal: HGlobal); var VisioAppl: Visio_TLB.IVApplication; iStrm: IStream; hres: HResult; begin iStrm := Nil; VisioAppl:= nil; hres := CreateStreamOnHGlobal(AHGlobal, FALSE, iStrm); if (SUCCEEDED(hres)) then begin hres := CoUnmarshalInterface(iStrm, Visio_TLB.IVApplication, VisioAppl); iStrm := nil; ShowMessage('Result:' + BoolToStr(SUCCEEDED(hres))); <-- result 0 ShowMessage(VisioAppl.ProductName); <---- Error end; end;

    Read the article

  • Problem with XStream Marshalling to return xml and json

    - by MiKu
    When i use new XStream().toXml(someObject); it returns following xml... <response> <status>SUCCESS</status> <isOwnershipVerified class="boolean">false</isOwnershipVerified> </response> and, when i use new XStream(new JsonHierarchicalStreamDriver()).toXml(someObject); it returns following json... {"response": { "status": "SUCCESS", "isOwnershipVerified": { "@class": "boolean""false"} }} Now, since i want to get rid of class attribute altogether (read it not to alias it with anything else, but to remove it) i use following code. XStream xStream = new XStream(); StringWriter writer = new StringWriter(); xStream.marshal(this, new PrettyPrintWriter(writer) { @Override public void addAttribute(final String key, final String value) { if (!key.equals("class")) { super.addAttribute(key, value); } } }); return writer.toString(); which gives follwing xml... <response> <status>SUCCESS</status> <isOwnershipVerified>false</isOwnershipVerified> </response> but, when i pass new JsonHierarchicalStreamDriver() while xStream object creation above, it does NOT return json. it returns the same xml shown above. What is wrong going on here? Thanks in advance...

    Read the article

  • Problem with Marshalling char* in c#

    - by chrmue
    I have a problem calling this function from a c++ DLL in c# INT32 WINAPI PM_COM_GetText(INT32 TextId, char* pBuf, INT32 BufSize); It writes a Text in a buffer for a given text id. I try to call it with the following c# code, but I constantly get an access violation and don't undrestand why: public string GetText(Int32 TextId) { Int32 BufSize = 256; StringBuilder Str = new StringBuilder(BufSize); PM_COM_GetText(TextId, Str, BufSize); return Str.ToString(); } [DllImport("ComDll.dll", CharSet = CharSet.Ansi)] private static extern Int32 PM_COM_GetText(Int32 TextId, StringBuilder Str, Int32 BufSize); I don't see what's wrong, it looks to me like many other code snippets I found in the web. Any ideas? Thanks in advance!

    Read the article

  • union marshalling issue in C#

    - by senthil
    I have union inside structure and the structure looks like struct tDeviceProperty { DWORD Tag; DWORD Size; union _DP value; }; typedef union _DP { short int i; LONG l; ULONG ul; float flt; double dbl; BOOL b; double at; FILETIME ft; LPSTR lpszA; LPWSTR lpszW; LARGE_INTEGER li; struct tBinary bin; BYTE reserved[40]; } __UDP; struct tBinary { ULONG size; BYTE * bin; }; from the tBinary structure bin has to be converted to tImage (structure is given below) struct tImage { DWORD x; DWORD y; DWORD z; DWORD Resolution; DWORD type; DWORD ID; diccid_t SourceID; const void *buffer; const char *Info; const char *UserImageID; }; to use the same in c# I have done marshaling but not giving proper values when converting the pointer to structure. The C# code is follows, tBinary tBin = new tBinary(); IntPtr tBinbuffer = Marshal.AllocCoTaskMem(Marshal.SizeOf(tBin)); Marshal.StructureToPtr(tBin.bin, tBinbuffer, false); tDeviceProperty tDevice = new tDeviceProperty(); tDevice.bin = tBinbuffer; IntPtr tDevicebuffer = Marshal.AllocCoTaskMem(Marshal.SizeOf(tDevice)); Marshal.StructureToPtr(tDevice.bin, tDevicebuffer, false); Battary tbatt = new Battary(); tbatt.value = tDevicebuffer; IntPtr tbattbuffer = Marshal.AllocCoTaskMem(Marshal.SizeOf(tbatt)); Marshal.StructureToPtr(tbatt.value, tbattbuffer, false); result = GetDeviceProperty(ref tbattbuffer); Battary v = (Battary)Marshal.PtrToStructure(tbattbuffer, typeof(Battary)); tDeviceProperty v2 = (tDeviceProperty)Marshal.PtrToStructure(tDevicebuffer, typeof(tDeviceProperty)); tBinary v3 = (tBinary)Marshal.PtrToStructure(tBinbuffer, typeof(tBinary));

    Read the article

  • JAXB Web Services: Multiple Object Marshalling

    - by Luke Evans
    I can marshal and unmarshal 1 object with no problems (in netbeans); I need to know how to do this with multiple objects? I can't generate anything but null pointer exceptions when trying to unmarshal 3 objects into an array from XML; so I don't even know if I've marshalled the 3 out correctly. I know the basic idea of declaring the object, then using the jaxbu or jaxbm command, but I'd like to see this working for more than one object. **TLDR: How do I marshal/unmarshal multiple objects of a single class into/out of XML?? THANKS Code I have that marshals one object from XML: try { JAXBContext jc = JAXBContext.newInstance ("myOffers"); Unmarshaller u = jc.createUnmarshaller (); myOffers.Offer flight = (myOffers.Offer) u.unmarshal( new FileInputStream( "offers.xml" )); System.out.println ("Airline is : " + flight.getAirline()); System.out.println ("Origin is : " + flight.getOrigin()); System.out.println ("Destination is : " + flight.getDestination()); System.out.println ("Seats available : " + flight.getSeats()); System.out.println("Proximity to City Centre is : " + flight.getProximity()); System.out.println("Currency : " + flight.fare.getCurrency()); System.out.println("Value : " + flight.fare.getValue()); } catch (JAXBException e) { System.out.println("Error " + e);} ok so the Xml is: <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <ns2:offer xmlns:ns2="http://simple.example.com/CInfoXmlDoc"> <Origin>Nottingham</Origin> <Destination>Istanbul</Destination> <Airline>Lufthansa</Airline> <Proximity>10</Proximity> <Seats>260</Seats> <Fare> <Currency>GBP</Currency> <Value>300</Value> </Fare> </ns2:offer> <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <ns2:offer xmlns:ns2="http://simple.example.com/CInfoXmlDoc"> <Origin>Birmingham</Origin> <Destination>Cairo</Destination> <Airline>Monarch</Airline> <Proximity>15</Proximity> <Seats>350</Seats> <Fare> <Currency>GBP</Currency> <Value>300</Value> </Fare> </ns2:offer> public static void main(String[] args) throws FileNotFoundException { int i = 0; int arraySize = 2; myOffers.Offer offer[] = new myOffers.Offer[arraySize]; offer[i] = new myOffers.Offer(); offer[i].fare = new myOffers.Offer.Fare(); offer[i].setAirline("Lufthansa"); offer[i].setOrigin("Nottingham"); offer[i].setDestination("Istanbul"); offer[i].setSeats(260); offer[i].setProximity(10); offer[i].fare.currency = "GBP"; offer[i].fare.value = 300; i++; offer[i] = new myOffers.Offer(); offer[i].fare = new myOffers.Offer.Fare(); offer[i].setAirline("Monarch"); offer[i].setOrigin("Birmingham"); offer[i].setDestination("Cairo"); offer[i].setSeats(350); offer[i].setProximity(15); offer[i].fare.currency = "GBP"; offer[i].fare.value = 300; try { int n = 0; FileOutputStream f = new FileOutputStream("offers.xml"); javax.xml.bind.JAXBContext jaxbCtx = javax.xml.bind.JAXBContext.newInstance(offer[n].getClass().getPackage().getName()); javax.xml.bind.Marshaller marshaller = jaxbCtx.createMarshaller(); marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_ENCODING, "UTF-8"); //NOI18N marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); while (n < arraySize) { marshaller.marshal(offer[n], f); n++; } } catch (javax.xml.bind.JAXBException ex) { // XXXTODO Handle exception java.util.logging.Logger.getLogger("global").log(java.util.logging.Level.SEVERE, null, ex); //NOI18N } } Which was generated by my marshal code found here: public static void main(String[] args) throws FileNotFoundException { int i = 0; int arraySize = 2; myOffers.Offer offer[] = new myOffers.Offer[arraySize]; offer[i] = new myOffers.Offer(); offer[i].fare = new myOffers.Offer.Fare(); offer[i].setAirline("Lufthansa"); offer[i].setOrigin("Nottingham"); offer[i].setDestination("Istanbul"); offer[i].setSeats(260); offer[i].setProximity(10); offer[i].fare.currency = "GBP"; offer[i].fare.value = 300; i++; offer[i] = new myOffers.Offer(); offer[i].fare = new myOffers.Offer.Fare(); offer[i].setAirline("Monarch"); offer[i].setOrigin("Birmingham"); offer[i].setDestination("Cairo"); offer[i].setSeats(350); offer[i].setProximity(15); offer[i].fare.currency = "GBP"; offer[i].fare.value = 300; try { int n = 0; FileOutputStream f = new FileOutputStream("offers.xml"); javax.xml.bind.JAXBContext jaxbCtx = javax.xml.bind.JAXBContext.newInstance(offer[n].getClass().getPackage().getName()); javax.xml.bind.Marshaller marshaller = jaxbCtx.createMarshaller(); marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_ENCODING, "UTF-8"); //NOI18N marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); while (n < arraySize) { marshaller.marshal(offer[n], f); n++; } } catch (javax.xml.bind.JAXBException ex) { // XXXTODO Handle exception java.util.logging.Logger.getLogger("global").log(java.util.logging.Level.SEVERE, null, ex); //NOI18N } } Apologies, I'm fining this editor quite appalling but thats another matter. Whats wrong with [code][/code] tags...

    Read the article

  • Marshalling a C structure to C#

    - by Hilbert
    Hi, I don't know how to marshall this structure in Mono. typedef struct rib_struct { rib_used_t used; rib_status_t status; rib_role_t role; uint8_t conf; rib_dc_t *pending; pthread_mutex_t mutex; pthread_cond_t cond; rib_f_t *props; } rib_t; And for example, rib_dc_t is like: typedef struct rib_dc_struct { uint16_t id; uint8_t min_id; uint8_t conf; struct rib_dc_struct *next; } rib_dc_t; I don't know how to marshall the pthread structures. And the pointers... should I use IntPtr or a managed structures? How to mashall the pointer in the last struct to the struct itself? Thanks in adanvaced

    Read the article

  • Quirks in .NET – Part 3 Marshalling Numbers

    - by thycotic
    Kevin has posted about marshalling numbers in the 3rd part of his ongoing blog series.   Jonathan Cogley is the CEO of Thycotic Software, an agile software services and product development company based in Washington DC.  Secret Server is our flagship enterprise password management product.

    Read the article

  • Why is the concept of Marshalling called as such?

    - by chickeninabiscuit
    I've always thought that the concept of Marshalling had a bit of a funny name. My mental conception of the process would always involve an ol' wildwest gunslinging marshall who would coerce objects into serialized form at gunpoint. I just found out the real reason Marshalling is called what it's called and chuckled. Do you know the real reason, or perhaps you too are familiar with my gunslinger?

    Read the article

  • How to add DOCTYPE and xml processing instructions when marshalling with JAXB?

    - by Juha Syrjälä
    I am marshalling (serializing) JAXB beans to output stream. How can I add DOCTYPE declaration and xml processing instructions to ouput? I am doing currently marshalling like this: JAXBContext jaxbContext = JAXBContext.newInstance("com.example.package"); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); Schema schema = schemaFactory.newSchema(schemaSource); marshaller.setSchema(schema); marshaller.marshal(object, output); I'd like have output that looks something like this: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE Something SYSTEM "some.dtd"> <?xml-stylesheet type="text/xsl" href="some.xsl"?> JAXB bean are generated code so I don't want to change them. There are some undocumented tricks to add the xml processing instructions and doctype. But what is the preferred or right way to do this?

    Read the article

  • Marshalling the value of a char* ANSI string DLL API parameter into a C# string

    - by Brian Biales
    For those who do not mix .NET C# code with legacy DLL's that use char* pointers on a regular basis, the process to convert the strings one way or the other is non-obvious. This is not a comprehensive article on the topic at all, but rather an example of something that took me some time to go find, maybe it will save someone else the time. I am utilizing a third party too that uses a call back function to inform my application of its progress.  This callback includes a pointer that under some circumstances is a pointer to an ANSI character string.  I just need to marshal it into a C# string variable.  Seems pretty simple, yes?  Well, it is, (as are most things, once you know how to do them). The parameter of my callback function is of type IntPtr, which implies it is an integer representation of a pointer.  If I know the pointer is pointing to a simple ANSI string, here is a simple static method to copy it to a C# string: private static string GetStringFromCharStar(IntPtr ptr) {     return System.Runtime.InteropServices.Marshal.PtrToStringAnsi(ptr); } The System.Runtime.InteropServices is where to look any time you are mixing legacy unmanaged code with your .NET application.

    Read the article

  • Using XSLT for messaging instead of marshalling/unmarshalling Java message objects

    - by Joost van Stuijvenberg
    So far I have been using either handmade or generated (e.g. JAXB) Java objects as 'carriers' for messages in message processing software such as protocol converters. This often leads to tedious programming, such as copying/converting data from one system's message object to an instance of another's system message object. And it sure brings in lots of Java code with getters and setters for each message attribute, validation code, etc. I was wondering whether it would be a good idea to convert one system's XML message into another system's format - or even convert requests into responses from the same system - using XSLT. This would mean I would no longer have to unmarshall XML streams to Java objects, copy/convert data using Java and marshall the resulting message object to another XML stream. Since each message may actually have a purpose I would 'link' the message (and the payload it contains in its properties or XML elements/attributes) to EXSLT functions. This would change my design approach from an imperative to a declarative style. Has anyone done this before and, if so, what are your experiences? Does the reduced amount of Java 'boiler plate' code weigh up to the increased complexity of (E)XSLT?

    Read the article

  • Marshalling C# Structs into DX11 cbuffers

    - by Craig
    I'm having some issues with the packing of my structure in C# and passing them through to cbuffers I have registered in HLSL. When I pack my struct in one manner the information seems to be able to pass to the shader: [StructLayout(LayoutKind.Explicit, Size = 16)] internal struct TestStruct { [FieldOffset(0)] public Vector3 mEyePosition; [FieldOffset(12)] public int type; } This works perfectly when used against this HLSL fragment: cbuffer PerFrame : register(b0) { Vector3 eyePos; int type; } float3 GetColour() { float3 returnColour = float(0.0f, 0.0f, 0.0f); switch(type) { case 0: returnColour = float3(1.0f, 0.0f, 0.0f); break; case 1: returnColour = float3(0.0f, 1.0f, 0.0f); break; case 2: returnColour = float3(0.0f, 0.0f, 1.0f); break; } return returnColour; } However, when I use the following structure definitions... // Note this is 16 because HLSL packs in 4 float 'chunks'. // It is also simplified, but still demonstrates the problem. [StructLayout(Layout.Explicit, Size = 16)] internal struct InternalTestStruct { [FieldOffset(0)] public int type; } [StructLayout(LayoutKind.Explicit, Size = 32)] internal struct TestStruct { [FieldOffset(0)] public Vector3 mEyePosition; //Missing 4 bytes here for correct packing. [FieldOffset(16)] public InternalTestStruct mInternal; } ... the following HLSL fragment no longer works. struct InternalType { int type; } cbuffer PerFrame : register(b0) { Vector3 eyePos; InternalType internalStruct; } float3 GetColour() { float3 returnColour = float(0.0f, 0.0f, 0.0f); switch(internaltype.type) { case 0: returnColour = float3(1.0f, 0.0f, 0.0f); break; case 1: returnColour = float3(0.0f, 1.0f, 0.0f); break; case 2: returnColour = float3(0.0f, 0.0f, 1.0f); break; } return returnColour; } Is there a problem with the way I am packing the struct, or is it another issue? To re-iterate: I can pass a struct in a cbuffer so long as it does not contain a nested struct.

    Read the article

  • Can I force JAXB not to convert " into &quot;, for example, when marshalling to XML?

    - by Elliot
    I have an Object that is being marshalled to XML using JAXB. One element contains a String that includes quotes ("). The resulting XML has &quot; where the " existed. Even though this is normally preferred, I need my output to match a legacy system. How do I force JAXB to NOT convert the HTML entities? -- Thank you for the replies. However, I never see the handler escape() called. Can you take a look and see what I'm doing wrong? Thanks! package org.dc.model; import java.io.IOException; import java.io.Writer; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import org.dc.generated.Shiporder; import com.sun.xml.internal.bind.marshaller.CharacterEscapeHandler; public class PleaseWork { public void prettyPlease() throws JAXBException { Shiporder shipOrder = new Shiporder(); shipOrder.setOrderid("Order's ID"); shipOrder.setOrderperson("The woman said, \"How ya doin & stuff?\""); JAXBContext context = JAXBContext.newInstance("org.dc.generated"); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); marshaller.setProperty(CharacterEscapeHandler.class.getName(), new CharacterEscapeHandler() { @Override public void escape(char[] ch, int start, int length, boolean isAttVal, Writer out) throws IOException { out.write("Called escape for characters = " + ch.toString()); } }); marshaller.marshal(shipOrder, System.out); } public static void main(String[] args) throws Exception { new PleaseWork().prettyPlease(); } } -- The output is this: <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <shiporder orderid="Order's ID"> <orderperson>The woman said, &quot;How ya doin &amp; stuff?&quot;</orderperson> </shiporder> and as you can see, the callback is never displayed. (Once I get the callback being called, I'll worry about having it actually do what I want.) --

    Read the article

  • How to Customize JAXB Marshalling if generating JAXB beans from XML

    - by Charles O.
    Hello, I want to customize the marshalling of dates in JAXB. It's a variant of this already asked question. I would think I would use an XMLAdapter, as this answer questions specifies. But I can't do that exactly, because I'm going the other way around, generating the JAXB beans from an .XSD -- I can't add annotations to the JAXB beans because they are generated code. I've tried calling Marshaller.setAdapter(), but with no luck. final Marshaller marshaller = getJaxbContext().createMarshaller(); marshaller.setSchema(kniSchema); marshaller.setAdapter(new DateAdapter()); ... private static class DateAdapter extends XmlAdapter<String, XMLGregorianCalendar> { @Override public String marshal(XMLGregorianCalendar v) throws Exception { return "hello"; //Just a test to see if it's working } @Override public XMLGregorianCalendar unmarshal(String v) throws Exception { return null; // Don't care about this for now } } Where the relevant part of my generated JAXB bean looks like this: @XmlSchemaType(name = "date") protected XMLGregorianCalendar activeSince; When I do this, what the default date/XMLGregorianCalendar marshalling happens. It's as if I didn't do it all. Any help is appreciated. Thanks, Charles

    Read the article

  • RESTEasy - simple string array/collection marshalling

    - by peperg
    Is there a simple way for marshalling and unmarshalling String[] or List in RESTEasy? My code sample : @GET @Path("/getSomething") @Produces(MediaType.APPLICATION_JSON) public List<String> getSomeData() { return Arrays.asList("a","b","c","d"); } Above gives me an Exception : Could not find MessageBodyWriter for response object of type: java.util.Arrays$ArrayList of media type: application/json

    Read the article

  • Marshalling polymorphic objects in JAX-WS

    - by pkchukiss
    I'm creating a JAX-WS type webservice, with operations that return an object WebServiceReply. The class WebServiceReply itself contains a field of type Object. The individual operations would populate that field with a few different data-types, depending on the operation. Publishing the WSDL (I'm using Netbeans 6.7), and getting a ASP.NET application to retrieve and parse the WSDL was fine, but when I tried to call an operation, I would receive the following exception: javax.xml.ws.WebServiceException: javax.xml.bind.MarshalException - with linked exception: [javax.xml.bind.JAXBException: class [LDataObject.Patient; nor any of its super class is known to this context.] How do I mark the annotations in the DataObject.Patient class, as well as the WebServiceReply class to get it to work? I haven't been able to fine a definitive resource on marshalling based upon annotations within the target classes either, so it would be great if anybody could point me to that too. WebServiceReply.java @XmlRootElement(name="WebServiceReply") public class WebServiceReply { private Object returnedObject; private String returnedType; private String message; private String errorMessage; .......... // Getters and setters follow } DataObject.Patient.java @XmlRootElement(name="Patient") public class Patient { private int uid; private Date versionDateTime; private String name; private String identityNumber; private List<Address> addressList; private List<ContactNumber> contactNumberList; private List<Appointment> appointmentList; private List<Case> caseList; } Solution (Thanks to Gregory Mostizky for his answer) I edited the WebServiceReply class so that all the possible return objects extend from a new class ReturnValueBase, and added the annotations using @XmlSeeAlso to ReturnValueBase. JAXB worked properly after that! Nonetheless, I'm still learning about JAXB marshalling in JAX-WS, so it would be great if anyone can still post any tutorial on this. Gregory: you might want to add-on to your answer that the return objects need to sub-class from ReturnValueBase. Thanks a lot for your help! I had been going bonkers over this problem for so long!

    Read the article

  • JAXB Marshalling supply name space for root element dynamically

    - by Venkat
    I have to pass the namespace for root element dynamically while marshalling using jaxb (JAXB 2.1.10 - JDK 6). i will be using the genrated xml to call different webservices which is qualified with different namespaces but same input xml. here is my sample jaxb annotated class .....guide me with your valuable inputs. @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "taskName", "taskType" }) @XmlRootElement(name = "TaskRequest") public class TaskRequest { @XmlElement(name = "TaskName", required = true) protected String taskName; @XmlElement(name = "TaskType", required = true) protected String taskType; public String getTaskName() { return taskName; } public void setTaskName(String value) { this.taskName = value; } public String getTaskType() { return taskType; } public void setTaskType(String value) { this.taskType = value; } }

    Read the article

  • Fastest way to access VB6 String in C#

    - by Simon Woods
    Hi I am using COMInterop. I have a call in VB6 which returns a string of roughly 13000 chars. If I execute the call in pure VB6 it takes about 800ms to execute. If I execute it via c# and COMInterop it takes about 8 seconds. I'm assuming the delay is caused by marshalling. If I am correct about marshalling, I'd be grateful if someone could suggest the fastest way I can get this into C#. e.g. Would it be better to a) expose it as a byte array b) provide a byref string param into the VB6 layer I would appreciate some sample code as well. I tried the Marshal.PtrToStringAuto(Marshal.ReadIntPtr(myCOMObject.GetString, 0) to no avail Many thx S

    Read the article

  • How to remove not required Elements from generated XML via jaxb

    - by Dangling Piyush
    I want to know if there is anyway for removing not required elements from generated xml using jaxb.I have my xsd element definition as follows. <xsd:element name="Title" maxOccurs="1" minOccurs="0"> <xsd:annotation> <xsd:documentation> A name given to the digital record. </xsd:documentation> </xsd:annotation> <xsd:simpleType> <xsd:restriction base="xsd:string"> <xsd:minLength value="1"></xsd:minLength> </xsd:restriction> </xsd:simpleType> </xsd:element> As you can see it is not a mandatory element because minOccurs="0" But if it is not empty the length should be 1. <xsd:minLength value="1"></xsd:minLength> At the time of marshalling if I left the Title field blank it is throwing the SAXException because of min-length restriction. So what I want to do is to remove the whole occurrence of <Title/> from generated XML.Right now i have removed the min-length restriction so it is adding the <Title> element as EMPTY <Title></Title> But I do not want it like this.Any help is appreciated.I am using jaxb 2.0 for Marshalling. UPDATE: Following is my variable definiton : private JAXBContext jaxbContext; private Unmarshaller unmarshaller; private SchemaFactory factory; private Schema schema; private Marshaller marshaller; Marshalling code. jaxbContext = JAXBContext.newInstance(ERecordType.class); marshaller = jaxbContext.createMarshaller(); factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); schema = factory.newSchema((new File(xsdLocation))); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); ERecordType e = new ERecordType(); e.setCataloging(rc); /** * Validate Against Schema. */ marshaller.setSchema(schema); /** * Marshal will throw an exception if XML not validated against * schema. */ marshaller.marshal(e, System.out);

    Read the article

  • Marshalling C# com items when using recursion

    - by Kevin
    I am using the SourceSafe COM object (SourceSafeTypeLib) from C# to automate a SourceSafe recursive get (part of a larger build process). The recursive function is shown below. How do I ensure that all the COM objects created in the foreach loop get released correctly? /// <summary> /// Recursively gets files/projects from SourceSafe (this is a recursive function). /// </summary> /// <param name="vssItem">The VSSItem to get</param> private void GetChangedFiles(VSSItem vssItem) { // 'If the object is a file perform the diff, // 'If not, it is a project, so use recursion to go through it if(vssItem.Type == (int)VSSItemType.VSSITEM_FILE) { bool bDifferent = false; //file is different bool bNew = false; //file is new //Surround the diff in a try-catch block. If a file is new(doesn't exist on //the local filesystem) an error will be thrown. Catch this error and record it //as a new file. try { bDifferent = vssItem.get_IsDifferent(vssItem.LocalSpec); } catch { //File doesn't exist bDifferent = true; bNew = true; } //If the File is different(or new), get it and log the message if(bDifferent) { if(bNew) { clsLog.WriteLine("Getting " + vssItem.Spec); } else { clsLog.WriteLine("Replacing " + vssItem.Spec); } string strGetPath = vssItem.LocalSpec; vssItem.Get(ref strGetPath, (int)VSSFlags.VSSFLAG_REPREPLACE); } } else //Item is a project, recurse through its sub items { foreach(VSSItem fileItem in vssItem.get_Items(false)) { GetChangedFiles(fileItem); } } }

    Read the article

  • Marshalling a big-endian byte collection into a struct in order to pull out values

    - by Pat
    There is an insightful question about reading a C/C++ data structure in C# from a byte array, but I cannot get the code to work for my collection of big-endian (network byte order) bytes. (EDIT: Note that my real struct has more than just one field.) Is there a way to marshal the bytes into a big-endian version of the structure and then pull out the values in the endianness of the framework (that of the host, which is usually little-endian)? This should summarize what I'm looking for (LE=LittleEndian, BE=BigEndian): void Main() { var leBytes = new byte[] {1, 0}; var beBytes = new byte[] {0, 1}; Foo fooLe = ByteArrayToStructure<Foo>(leBytes); Foo fooBe = ByteArrayToStructureBigEndian<Foo>(beBytes); Assert.AreEqual(fooLe, fooBe); } [StructLayout(LayoutKind.Explicit, Size=2)] public struct Foo { [FieldOffset(0)] public ushort firstUshort; } T ByteArrayToStructure<T>(byte[] bytes) where T: struct { GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned); T stuff = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(),typeof(T)); handle.Free(); return stuff; } T ByteArrayToStructureBigEndian<T>(byte[] bytes) where T: struct { ??? }

    Read the article

1 2 3 4 5 6  | Next Page >