Search Results

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

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

  • DllImport and char*

    - by Malfist
    I have a method I want to import from a DLL and it has a signature of: BOOL GetDriveLetter(OUT char* DriveLetter) I've tried [DllImport("mydll.dll")] public static extern bool GetDriveLetter(byte[] DriveLetter); and [DllImport("mydll.dll")] public static extern bool GetDriveLetter(StringBuilder DriveLetter); but neither returned anything in the DriveLetter variable.

    Read the article

  • How can I marshall between XLOPER and VARIANT?

    - by Tim
    I'm working on an Excel plugin (XLL), which communicates with COM objects. So, I have to marshall between XLOPER and VARIANT. I've got most of this working, but arrays are definitely a pain. I need to support 1- and 2D arrays. I imagine someone has already had to deal with this before. Is there some library available to simplify this? Are there good tools for dealing with VARIANT, SAFEARRAY, and XLOPER (and XLOPER12)?

    Read the article

  • Can JAXB Incrementally Marshall An Object?

    - by Intellectual Tortoise
    I've got a fairly simple, but potentially large structure to serialize. Basically the structure of the XML will be: <simple_wrapper> <main_object_type> <sub_objects> </main_object_type> ... main_object_type repeats up to 5,000 times </simple_wrapper> The main_object_type can have a significant amount of data. On my first 3,500 record extract, I had to give the JVM way more memory than it should need. So, I'd like to write out to disk after each (or a bunch of) main_object_type. I know that setting Marshaller.JAXB_FRAGMENT would allow it fragments, but I loose the outer xml document tags and the <simple_wrapper>. Any suggestions?

    Read the article

  • Parsing plain Win32 PE File (Exe/DLL) in C#.NET

    - by Usman
    Hello, I need to parse plain Win32 DLL/Exe and need to get all imports and exports from it and to show it on console or GUI(say Win Forms). Is it possible to parse Win32 DLL/Exe in C#.NET, read its export table,import table and get managed types from it. As its unmanaged PE(.NET doesn't allows you to convert unmanaged PE files to managed .NET assemblies, only it generates COM managed assemblies). So how to parse export and import tables of PE files and take all methods(signatures from it) in managed form.(e.g if char* as argument, it should display as IntPtr) Regards Usman

    Read the article

  • Marshaling an array of IntPtrs in C#

    - by mcoolbeth
    From safe, managed code in C#, I would like to call a function in a C API that receives an array of pointers (void**). I have the corresponding managed array of IntPtr objects, but the Marshal methods advertised in the documentation at MSDN do not seem sufficient to provide and IntPtr to an unmanaged block of memory with the correct content. I had hoped to obtain an IntPtr with 'Marshal.AllocHGlobal' and then assign the correct content using 'Marshal.Copy', but it seems the function has not been overloaded for an array of IntPtr. Any thoughts on the best way to do this? Thanks in advance.

    Read the article

  • Convert a byte array to a class containing a byte array in C#

    - by Mathijs
    I've got a C# function that converts a byte array to a class, given it's type: IntPtr buffer = Marshal.AllocHGlobal(rawsize); Marshal.Copy(data, 0, buffer, rawsize); object result = Marshal.PtrToStructure(buffer, type); Marshal.FreeHGlobal(buffer); I use sequential structs: [StructLayout(LayoutKind.Sequential)] public new class PacketFormat : Packet.PacketFormat { } This worked fine, until I tried to convert to a struct/class containing a byte array. [StructLayout(LayoutKind.Sequential)] public new class PacketFormat : Packet.PacketFormat { public byte header; public byte[] data = new byte[256]; } Marshal.SizeOf(type) returns 16, which is too low (should be 257) and causes Marshal.PtrToStructure to fail with the following error: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. I'm guessing that using a fixed array would be a solution, but can it also be done without having to resort to unsafe code?

    Read the article

  • Marshal struct to unmanaged array

    - by Pedro
    Hi guys, I have a C# struct to represent a cartesian vector, something like this: public struct Vector { private double x; private double y; private double z; //Some properties/methods } Now I have an unmanaged C dll that I need to call with P/Invoke. Some methods expect a double[3] parameter. The unmanaged C signature is something like void Cross(double a[3], double b[3], double c[3]); Is there any way to set up a P/Invoke signature so I can pass instances of my Vector struct and marshal them transparently to unmanaged double[3]? I would also need bidirectional marshaling as the unmanaged function needs to write the output to the argument array, so I guess I would need to marshal as LpArray. Any ideas? Thanks Pedro

    Read the article

  • Custom string formatting in Grails JSON marshaller

    - by ethaler
    I am looking for a way to do some string formatting through Grails JSON conversion, similar to custom formatting dates, which I found in this post. Something like this: import grails.converters.JSON; class BootStrap { def init = { servletContext -> JSON.registerObjectMarshaller(String) { return it?.trim() } } def destroy = { } } I know custom formatting can be done on a per domain class basis, but I am looking for a more global solution.

    Read the article

  • How can I find out if an instance is a MarshalByRef proxy?

    - by Will
    I know there's a way, I know I've done it (a long time) before, but I can't remember or find out how to do it!!! var otherDomain = AppDomain.Create("Lol my memory sucks"); var myRemotableType = typeof(MyTypeThatExtendsMBRO); var proxy = otherDomain .CreateInstanceAndUnwrap( type.Assembly.FullName, type.FullName); // how do you do this next step??? bool isProxy = IsYouIsOrIsYouAintAProxy(proxy);

    Read the article

  • Spring with Castor - Null Pointer Exception when initialising Application Context

    - by babyangel86
    Hi, I'm trying to register my castor mapping files with spring and I appear to be getting a null pointer exception. In my application context I have: <bean id="xmlContext" class="org.castor.spring.xml.XMLContextFactoryBean"> <property name="mappingLocations"> <list> <value>DistributionSamplerMappings.xml</value> </list> </property> <property name="castorProperties"> <props> <prop key="org.exolab.castor.xml.strictelements">false</prop> </props> </property> </bean> <bean id="marshaller" class="org.castor.spring.xml.CastorMarshallerFactoryBean"> <property name="xmlContext"><ref local="xmlContext"/></property> </bean> <bean id="unmarshaller" class="org.castor.spring.xml.CastorUnmarshallerFactoryBean"> <property name="xmlContext"> <ref local="xmlContext"/></property> <property name="ignoreExtraElements"><value>true</value></property> <property name="ignoreExtraAttributes"><value>true</value></property> </bean> Where DistributionSamplerMappings.xml lives in the same dir as the application context. I've tried using the spring-xml jar 1.2.1 and 1.5.3. but none of them seem to help. The exception being thrown back is: SEVERE: Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'xmlContext' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.NullPointerException at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1338) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:473) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409) at java.security.AccessController.doPrivileged(Native Method) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:423) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:728) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:380) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:255) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3830) at org.apache.catalina.core.StandardContext.start(StandardContext.java:4337) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045) at org.apache.catalina.core.StandardHost.start(StandardHost.java:719) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045) at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443) at org.apache.catalina.core.StandardService.start(StandardService.java:516) at org.apache.catalina.core.StandardServer.start(StandardServer.java:710) at org.apache.catalina.startup.Catalina.start(Catalina.java:566) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413) Caused by: java.lang.NullPointerException at org.castor.spring.xml.XMLContextFactoryBean.afterPropertiesSet(XMLContextFactoryBean.java:118) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1369) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1335) ... 30 more I'm using Spring 2.5.6 and Castor 1.3.1. Looking around I find I'm not the only one who has had this problem, but I don't seem to be able to find a solution. Any help would be much appreciated.

    Read the article

  • Most efficient way to send images across processes

    - by Heinrich Ulbricht
    Goal Pass images generated by one process efficiently and at very high speed to another process. The two processes run on the same machine and on the same desktop. The operating system may be WinXP, Vista and Win7. Detailled description The first process is solely for controlling the communication with a device which produces the images. These images are about 500x300px in size and may be updated up to several hundred times per second. The second process needs these images to display them. The first process uses a third party API to paint the images from the device to a HDC. This HDC has to be provided by me. Note: There is already a connection open between the two processes. They are communicating via anonymous pipes and share memory mapped file views. Thoughts How would I achieve this goal with as little work as possible? And I mean both work for me and the computer. I am using Delphi, so maybe there is some component available for doing this? I think I could always paint to any image component's HDC, save the content to memory stream, copy the contents via the memory mapped file, unpack it on the other side and paint it there to the destination HDC. I also read about a IPicture interface which can be used to marshall images. What are your ideas? I appreciate every thought on this!

    Read the article

  • Receiving an object in a unmanaged callback function

    - by Daniel Baulig
    Eg. I have following delegate method I want to use as a callback function with unmanaged code: public delegate void Callback(IntPtr myObject); Callback callback; I register it in the following way: [DllImport("a.dll")] public static void registerCallback(IntPtr callbackFunction, IntPtr anObject); // ... this.myObject = new MyClass(); this.objectPin = GCHandle.Alloc(this.myObject, GCHandleType.Pinned); registerCallback(Marshal.GetFunctionPointerForDelegate(callback), objectPin.AddrOfPinnedObject()); Now whenever the callback function is called it will have a Pointer/Handle of an object of the MyClass class. I could use Marshal.PtrToStructure to convert this to an object of MyClass. However, what I would like to have is that the delegate definition already contains the class MyClass. eg.: public delegate void Callback(MyClass myObject); I tried this, but it will not work. I also tried the following, which did not work: public delegate void Callback([MarshalAs(UnmanagedType.IUnknown)]MyClass myObject); I suppose I would need something like "UnmarshalAs" at this point, but sadly this is not available. Any suggestions how I could get lost of that IntPtr in my callback function and get a it packed up as a regular, managed MyClass object?

    Read the article

  • Marshal a C# struct to C++ VARIANT

    - by jortan
    To start with, I'm not very familiar with the COM-technology, this is the first time I'm working with it so bear with me. I'm trying to call a COM-object function from C#. This is the interface in the idl-file: [id(6), helpstring("vConnectInfo=ConnectInfoType")] HRESULT ConnectTarget([in,out] VARIANT* vConnectInfo); This is the interop interface I got after running tlbimp: void ConnectTarget(ref object vConnectInfo); The c++ code in COM object for the target function: STDMETHODIMP PCommunication::ConnectTarget(VARIANT* vConnectInfo) { if (!((vConnectInfo->vt & VT_ARRAY) && (vConnectInfo->vt & VT_BYREF))) { return E_INVALIDARG; } ConnectInfoType *pConnectInfo = (ConnectInfoType *)((*vConnectInfo->pparray)->pvData); ... } This COM-object is running in another process, it is not in a dll. I can add that the COM object is also used from another program written in C++. In that case there is no problem because in C++ a VARIANT is created and pparray-pvData is set to the connInfo data-structure and then the COM-object is called with the VARIANT as parameter. In C#, as I understand, my struct should be marshalled as a VARIANT automatically. These are two methods I've been using (or actually I've tried a lot more...) to call this method from C#: private void method1_Click(object sender, EventArgs e) { pcom.PCom PCom = new pcom.PCom(); pcom.IGeneralManagementServices mgmt = (pcom.IGeneralManagementServices)PCom; m_ci = new ConnectInfoType(); fillConnInfo(ref m_ci); mgmt.ConnectTarget(m_ci); } In the above case the struct gets marshalled as VT_UNKNOWN. This is a simple case and works if the parameter is not a struct (eg. works for int). private void method4_Click(object sender, EventArgs e) { ConnectInfoType ci = new ConnectInfoType(); fillConnInfo(ref ci); pcom PCom = new pcom.PCom(); pcom.IGeneralManagementServices mgmt = (pcom.IGeneralManagementServices)PCom; ParameterModifier[] pms = new ParameterModifier[1]; ParameterModifier pm = new ParameterModifier(1); pm[0] = true; pms[0] = pm; object[] param = new object[1]; param[0] = ci; object[] args = new object[1]; args[0] = param; mgmt.GetType().InvokeMember("ConnectTarget", BindingFlags.InvokeMethod, null, mgmt, args, pms, null, null); } In this case it gets marshalled as VT_ARRAY | VT_BYREF | VT_VARIANT. The problem is that when debugging the "target-function" ConnectTarget I cannot find the data I send in the SAFEARRAY-struct (or in any other place in memory either) What do I do with a VT_VARIANT? Any ideas on how to get my struct-data? Update: The ConnectInfoType struct: [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public class ConnectInfoType { public short network; public short nodeNumber; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 51)] public string connTargPassWord; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)] public string sConnectId; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)] public string sConnectPassword; public EnuConnectType eConnectType; public int hConnectHandle; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)] public string sAccessPassword; }; And the corresponding struct in c++: typedef struct ConnectInfoType { short network; short nodeNumber; char connTargPassWord[51]; char sConnectId[8]; char sConnectPassword[16]; EnuConnectType eConnectType; int hConnectHandle; char sAccessPassword[8]; } ConnectInfoType;

    Read the article

  • c# interop with ghostscript

    - by yodaj007
    I'm trying to access some Ghostscript functions like so: [DllImport(@"C:\Program Files\GPLGS\gsdll32.dll", EntryPoint = "gsapi_revision")] public static extern int Foo(gsapi_revision_t x, int len); public struct gsapi_revision_t { [MarshalAs(UnmanagedType.LPTStr)] string product; [MarshalAs(UnmanagedType.LPTStr)] string copyright; long revision; long revisiondate; } public static void Main() { gsapi_revision_t foo = new gsapi_revision_t(); Foo(foo, Marshal.SizeOf(foo)); This corresponds with these definitions from the iapi.h header from ghostscript: typedef struct gsapi_revision_s { const char *product; const char *copyright; long revision; long revisiondate; } gsapi_revision_t; GSDLLEXPORT int GSDLLAPI gsapi_revision(gsapi_revision_t *pr, int len); But my code is reading nothing into the string fields. If I add 'ref' to the function, it reads gibberish. However, the following code reads in the data just fine: public struct gsapi_revision_t { IntPtr product; IntPtr copyright; long revision; long revisiondate; } public static void Main() { gsapi_revision_t foo = new gsapi_revision_t(); IntPtr x = Marshal.AllocHGlobal(20); for (int i = 0; i < 20; i++) Marshal.WriteInt32(x, i, 0); int result = Foo(x, 20); IntPtr productNamePtr = Marshal.ReadIntPtr(x); IntPtr copyrightPtr = Marshal.ReadIntPtr(x, 4); long revision = Marshal.ReadInt64(x, 8); long revisionDate = Marshal.ReadInt64(x, 12); byte[] dest = new byte[1000]; Marshal.Copy(productNamePtr, dest, 0, 1000); string name = Read(productNamePtr); string copyright = Read(copyrightPtr); } public static string Read(IntPtr p) { List<byte> bits = new List<byte>(); int i = 0; while (true) { byte b = Marshal.ReadByte(new IntPtr(p.ToInt64() + i)); if (b == 0) break; bits.Add(b); i++; } return Encoding.ASCII.GetString(bits.ToArray()); } So what am I doing wrong with marshaling?

    Read the article

  • What is the best way to marshal a char array function argument?

    - by Seh Hui 'Felix' Leong
    Let say that given the following signature in LegacyLib.dll: int Login(SysInst *inst, char username[8], char password[6]); The simple way to marshal this function in C# would be: [DllImport("LegacyLib.dll", CharSet=CharSet.Ansi)] public static extern int Login(ref SysInst inst, string username, string password); The problem of doing it in a such a naive way is that the managed string we passed into the username or password parameter could be longer than the array bounds and this could potentially cause a buffer overrun in LegacyLib.dll. Is there a better way which overcomes this problem? i.e. is there any quick [MarshalAs(…)] magic that I could use to counter that?

    Read the article

  • Json <-> Java serialization that works with GWT

    - by amartynov
    I am looking for a simple Json (de)serializer for Java that might work with GWT. I have googled a bit and found some solutions that either require annotate every member or define useless interfaces. Quite a boring. Why don't we have something really simple like class MyBean { ... } new GoodSerializer().makeString(new MyBean()); new GoodSerializer().makeObject("{ ... }", MyBean.class)

    Read the article

  • Employing elegance in order to evade importing elephants: a case of excessive dll Imports

    - by user994179
    I am writing C# code that interfaces to a legacy (Feb 2012) C program, using DllImport. It works fine, but I need to call more than 30 different functions, turning my normally impeccable, exquisite code into something of near-elephantine proportions. Surely there must be a way around this? [Warning: those with weak stomachs may want to avert their eyes from what follows]: [DllImport("C:\\Users\\mitt\\Documents\\Visual Studio 2010\\Projects\\mrSolution\\mr\\x64\\Debug\\mrDll.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] public static extern bool mrEngine_initialize( [In, Out, MarshalAs(UnmanagedType.LPStruct)] PLOT_SPEC PlotSpec); [DllImport("C:\\Users\\mitt\\Documents\\Visual Studio 2010\\Projects\\mrSolution\\mr\\x64\\Debug\\mrDll.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] public static extern bool mrEngine_getDataPoint( [In, Out, MarshalAs(UnmanagedType.LPStruct)] PLOT_SPEC PlotSpec);

    Read the article

  • Parsing plain Win32 PE File (Exe/DLL) in .NET

    - by Usman
    I need to parse plain Win32 DLL/Exe and need to get all imports and exports from it and to show it on console or GUI(say Win Forms). Is it possible to parse Win32 DLL/Exe in C#.NET, read its export table,import table and get managed types from it. As its unmanaged PE(.NET doesn't allows you to convert unmanaged PE files to managed .NET assemblies, only it generates COM managed assemblies). So how to parse export and import tables of PE files and take all methods(signatures from it) in managed form.(e.g if char* as argument, it should display as IntPtr)

    Read the article

  • How can I pass managed objects from one AppDomain to another?

    - by Dennis P
    I have two assemblies that I'm trying to link together. One is a sort of background process that's built with WinForms and will be designed to run as a Windows Service. I have a second project that will act as a UI for the background process whenever a user launches it. I've never tried attempting something like this with managed code before, so I've started trying to use windows messages to communicate between the two processes. I'm struggling when it comes to passing more than just IntPtrs back and forth, however. Here's the code from a control in my UI project that registers itself with the background process: public void Init() { IntPtr hwnd = IntPtr.Zero; Process[] ps = Process.GetProcessesByName("BGServiceApp"); Process mainProcess = null; if(ps == null || ps.GetLength(0) == 0) { mainProcess = LaunchApp(); } else { mainProcess = ps[0]; } SendMessage(mainProcess.MainWindowHandle, INIT_CONNECTION, this.Handle, IntPtr.Zero); } protected override void WndProc(ref Message m) { if(m.Msg == INIT_CONFIRMED && InitComplete != null) { string message = Marshal.PtrToStringAuto(m.WParam); Marshal.FreeHGlobal(m.WParam); InitComplete(message, EventArgs.Empty); } base.WndProc(ref m); } This is the code from the background process that's supposed to receive a request from the UI process to register for status updates and send a confirmation message. protected override void WndProc(ref Message m) { if(m.Msg == INIT_CONNECTION) { RegisterUIDispatcher(m.WParam); Respond(m.WParam); } if(m.Msg == UNINIT_CONNECTION) { UnregisterUIDispatcher(m.WParam); if(m_RegisteredDispatchers.Count == 0) { this.Close(); } } base.WndProc(ref m); } private void Respond(IntPtr caller) { string test = "Registration confirmed!"; IntPtr ptr = Marshal.StringToHGlobalAuto(test); SendMessage(caller, INIT_CONFIRMED, ptr, IntPtr.Zero); } } The UI process receives the INIT_CONFIRMED message from my background process, but when I try to marshal the IntPtr back into a string, I get an empty string. Is the area of heap I'm using out of scope to the other process or am I missing some security attribute maybe? Is there a better and cleaner way to go about something like this using an event driven model?

    Read the article

  • Marshal managed string[] to unmanaged char**

    - by Vince
    This is my c++ struct (Use Multi-Byte Character Set) typedef struct hookCONFIG { int threadId; HWND destination; const char** gameApps; const char** profilePaths; } HOOKCONFIG; And .Net struct [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public struct HOOKCONFIG { public int threadId; public IntPtr destination; // MarshalAs? public string[] gameApps; // MarshalAs? public string[] profilePaths; } I got some problem that how do I marshal the string array? When I access the struct variable "profilePaths" in C++ I got an error like this: An unhandled exception of type 'System.AccessViolationException' occurred in App.exe Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. MessageBox(0, cfg.profilePaths[0], "Title", MB_OK); // error ... Orz

    Read the article

  • Convert between python array and .NET Array

    - by dungema
    I have a python method that returns a Python byte array.array('c'). Now, I want to copy this array using System.Runtime.InteropServices.Marshal.Copy. This method however expects a .NET array. import array from System.Runtime.InteropServices import Marshal bytes = array.array('c') bytes.append('a') bytes.append('b') bytes.append('c') Marshal.Copy(bytes, dest, 0, 3) Is there a way to make this work without copying the data? If not, how do I convert the data in the Python array to the .NET array?

    Read the article

  • IntPtr arithmetics

    - by Luca
    I tried to allocate an array of structs in this way: struct T { int a; int b; } data = Marshal.AllocHGlobal(count*Marshal.SizeOf(typeof(T)); ... I'd like to access to allocated data "binding" a struct to each element in array allocated with AllocHGlobal... something like this T v; v = (T)Marshal.PtrToStructure(data+1, typeof(T)); but i don't find any convenient way... why IntPtr lack of arithmetics? How can I workaround this is a "safe" way? Someone could confirm that PtrToStructure function copy data into the struct variable? In other words, modifing the struct reflect modifications in the structure array data, or not? Definitely, I want to operate on data pointed by an IntPtr using struct, without copying data each time, avoiding unsafe code. Thank all!

    Read the article

  • How to marshal structs with unknown length string fields in C#

    - by Ofir
    Hi all, I get an array of bytes, I need to unmarshal it to C# struct. I know the type of the struct, it has some strings fields. The strings in the byte array appears as so: two first bytes are the length of the string, then the string itself. I don;t know the length of the strings. I do know that its Unicode! [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public class User { int Id;//should be 1 String UserName;//should be OFIR String FullName;//should be OFIR } the byte array looks like so: 00,00,01,00, 00,00,08,00, 4F,00,46,00,49,00,52,00, 00,00,08,00, 4F,00,46,00,49,00,52,00, I also found this link with same problem unsolved: loading binary data into a structure Thank you all, Ofir

    Read the article

  • How do I add array indices to the XML produced by JAXB?

    - by oconnor0
    I have a Java bean ala @XmlRootElement public class Bean { @XmlElementWrapper(name = "ints") @XmlElement(name = "int") int[] values; // constructors, getters, setters, etc... } JAXB is producing XML like <bean> <ints> <int>12</int> <int>34</int> <int>56</int> </ints> </bean> I would like the array indices to be included on the <int> tags as array position conveys important value. Preferably as attributes like <bean> <ints> <int id='0'>12</int> <int id='1'>34</int> <int id='2'>56</int> </ints> </bean> Is there a way to do this?

    Read the article

  • Is it possible to pass a structure of delegates from managed to native?

    - by Veiva
    I am writing a wrapper for the game programming library "Allegro" and its less stable 4.9 branch. Now, I have done good insofar, except for when it comes to wrapping a structure of function pointers. Basically, I can't change the original code, despite having access to it, because that would require me to fork it in some manner. I need to know how I can somehow pass a structure of delegates from managed to native without causing an AccessViolationException that has occurred so far. Now, for the code. Here is the Allegro definition of the structure: typedef struct ALLEGRO_FILE_INTERFACE { AL_METHOD(ALLEGRO_FILE*, fi_fopen, (const char *path, const char *mode)); AL_METHOD(void, fi_fclose, (ALLEGRO_FILE *handle)); AL_METHOD(size_t, fi_fread, (ALLEGRO_FILE *f, void *ptr, size_t size)); AL_METHOD(size_t, fi_fwrite, (ALLEGRO_FILE *f, const void *ptr, size_t size)); AL_METHOD(bool, fi_fflush, (ALLEGRO_FILE *f)); AL_METHOD(int64_t, fi_ftell, (ALLEGRO_FILE *f)); AL_METHOD(bool, fi_fseek, (ALLEGRO_FILE *f, int64_t offset, int whence)); AL_METHOD(bool, fi_feof, (ALLEGRO_FILE *f)); AL_METHOD(bool, fi_ferror, (ALLEGRO_FILE *f)); AL_METHOD(int, fi_fungetc, (ALLEGRO_FILE *f, int c)); AL_METHOD(off_t, fi_fsize, (ALLEGRO_FILE *f)); } ALLEGRO_FILE_INTERFACE; My simple attempt at wrapping it: public delegate IntPtr AllegroInternalOpenFileDelegate(string path, string mode); public delegate void AllegroInternalCloseFileDelegate(IntPtr file); public delegate int AllegroInternalReadFileDelegate(IntPtr file, IntPtr data, int size); public delegate int AllegroInternalWriteFileDelegate(IntPtr file, IntPtr data, int size); public delegate bool AllegroInternalFlushFileDelegate(IntPtr file); public delegate long AllegroInternalTellFileDelegate(IntPtr file); public delegate bool AllegroInternalSeekFileDelegate(IntPtr file, long offset, int where); public delegate bool AllegroInternalIsEndOfFileDelegate(IntPtr file); public delegate bool AllegroInternalIsErrorFileDelegate(IntPtr file); public delegate int AllegroInternalUngetCharFileDelegate(IntPtr file, int c); public delegate long AllegroInternalFileSizeDelegate(IntPtr file); [StructLayout(LayoutKind.Sequential, Pack = 0)] public struct AllegroInternalFileInterface { [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalOpenFileDelegate fi_fopen; [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalCloseFileDelegate fi_fclose; [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalReadFileDelegate fi_fread; [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalWriteFileDelegate fi_fwrite; [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalFlushFileDelegate fi_fflush; [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalTellFileDelegate fi_ftell; [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalSeekFileDelegate fi_fseek; [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalIsEndOfFileDelegate fi_feof; [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalIsErrorFileDelegate fi_ferror; [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalUngetCharFileDelegate fi_fungetc; [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalFileSizeDelegate fi_fsize; } I have a simple auxiliary wrapper that turns an ALLEGRO_FILE_INTERFACE into an ALLEGRO_FILE, like so: #define ALLEGRO_NO_MAGIC_MAIN #include <allegro5/allegro5.h> #include <stdlib.h> #include <string.h> #include <assert.h> __declspec(dllexport) ALLEGRO_FILE * al_aux_create_file(ALLEGRO_FILE_INTERFACE * fi) { ALLEGRO_FILE * file; assert(fi && "`fi' null"); file = (ALLEGRO_FILE *)malloc(sizeof(ALLEGRO_FILE)); if (!file) return NULL; file->vtable = (ALLEGRO_FILE_INTERFACE *)malloc(sizeof(ALLEGRO_FILE_INTERFACE)); if (!(file->vtable)) { free(file); return NULL; } memcpy(file->vtable, fi, sizeof(ALLEGRO_FILE_INTERFACE)); return file; } __declspec(dllexport) void al_aux_destroy_file(ALLEGRO_FILE * f) { assert(f && "`f' null"); assert(f->vtable && "`f->vtable' null"); free(f->vtable); free(f); } Lastly, I have a class that accepts a Stream and provides the proper methods to interact with the stream. Just to make sure, here it is: /// <summary> /// A semi-opaque data type that allows one to load fonts, etc from a stream. /// </summary> public class AllegroFile : AllegroResource, IDisposable { AllegroInternalFileInterface fileInterface; Stream fileStream; /// <summary> /// Gets the file interface. /// </summary> internal AllegroInternalFileInterface FileInterface { get { return fileInterface; } } /// <summary> /// Constructs an Allegro file from the stream provided. /// </summary> /// <param name="stream">The stream to use.</param> public AllegroFile(Stream stream) { fileStream = stream; fileInterface = new AllegroInternalFileInterface(); fileInterface.fi_fopen = Open; fileInterface.fi_fclose = Close; fileInterface.fi_fread = Read; fileInterface.fi_fwrite = Write; fileInterface.fi_fflush = Flush; fileInterface.fi_ftell = GetPosition; fileInterface.fi_fseek = Seek; fileInterface.fi_feof = GetIsEndOfFile; fileInterface.fi_ferror = GetIsError; fileInterface.fi_fungetc = UngetCharacter; fileInterface.fi_fsize = GetLength; Resource = AllegroFunctions.al_aux_create_file(ref fileInterface); if (!IsValid) throw new AllegroException("Unable to create file"); } /// <summary> /// Disposes of all resources. /// </summary> ~AllegroFile() { Dispose(); } /// <summary> /// Disposes of all resources used. /// </summary> public void Dispose() { if (IsValid) { Resource = IntPtr.Zero; // Should call AllegroFunctions.al_aux_destroy_file fileStream.Dispose(); } } IntPtr Open(string path, string mode) { return IntPtr.Zero; } void Close(IntPtr file) { fileStream.Close(); } int Read(IntPtr file, IntPtr data, int size) { byte[] d = new byte[size]; int read = fileStream.Read(d, 0, size); Marshal.Copy(d, 0, data, size); return read; } int Write(IntPtr file, IntPtr data, int size) { byte[] d = new byte[size]; Marshal.Copy(data, d, 0, size); fileStream.Write(d, 0, size); return size; } bool Flush(IntPtr file) { fileStream.Flush(); return true; } long GetPosition(IntPtr file) { return fileStream.Position; } bool Seek(IntPtr file, long offset, int whence) { SeekOrigin origin = SeekOrigin.Begin; if (whence == 1) origin = SeekOrigin.Current; else if (whence == 2) origin = SeekOrigin.End; fileStream.Seek(offset, origin); return true; } bool GetIsEndOfFile(IntPtr file) { return fileStream.Position == fileStream.Length; } bool GetIsError(IntPtr file) { return false; } int UngetCharacter(IntPtr file, int character) { return -1; } long GetLength(IntPtr file) { return fileStream.Length; } } Now, when I do something like this: AllegroFile file = new AllegroFile(new FileStream("Test.bmp", FileMode.Create, FileAccess.ReadWrite)); bitmap.SaveToFile(file, ".bmp"); ...I get an AccessViolationException. I think I understand why (the garbage collector can relocate structs and classes whenever), but I'd think that the method stub that is created by the framework would take this into consideration and route the calls to the valid classes. However, it seems obviously so that I'm wrong. So basically, is there any way I can successfully wrap that structure? (And I'm sorry for all the code! Hope it's not too much...)

    Read the article

< Previous Page | 1 2 3 4 5 6  | Next Page >