Articles

Blog Migrated

In Uncategorized on December 3, 2011 by MT

I have migrated this blog to blog.mtarek.com, because a plain/boring web address is always the way to go ! I will stop using this one as of today. Although I may keep it online for sentimental purposes.🙂

Articles

Disable linking against cygwin1.dll

In Programming on December 1, 2011 by MT Tagged: , , , , , , ,

When developing for windows using cygwin gcc, cygwin uses its shared library cygwin1.dll for providing the c standard library for your application.

Usually people don’t want to ship the cygwin1.dll file with their binaries, so to avoid this and link against the MS C libraries, you have to provide the flag “-mno-cygwin” to gcc.

If you’re developing using eclipse you should add this flag to:

Project->Properties->C/C++ Build->Settings->Cygwin C Compiler->Miscellaneous->Other Flags

and

Project->Properties->C/C++ Build->Settings->Cygwin C Linkerompiler->Miscellaneous->Linker Flags

Articles

Marshaling Structs Between C and C# Part 1: Struct Pointers and Arrays

In Programming on November 28, 2011 by MT Tagged: , , , , , ,

I have finally been able to correctly pass complex structs back and forth between some client code written in C# and a library written in C.

There are many scenarios where you would need such interfacing between managed and unmanaged code, examples include – but are not limited to – reusing legacy code, or some constraint on the library – like speed or portability – that makes C an obviously better choice than C#.

While I was working on this, I couldn’t find what I needed to know easily. So this is an attempt to gather my findings in one place so that hopefully someone would benefit from it later.

Back to the main topic, one of the trickiest parts of code to work with here are structs, for one obvious reason; A struct can contain any datatype from primitives like ints and floats to arrays, pointers to other structs and pointers to functions.

Let’s start with a relatively simple case:

C Code :


struct SomeStruct
{
    int a;
    int b;
};

struct MarshalStruct
{
    int x;
    int y;
    struct SomeStruct* ptrToSomeStruct;
};
__dllspec(dllexport) void __cdecl func1(struct MarshalStruct* ms)
{
    ms->ptrToSomeStruct = calloc(1, sizeof(struct SomeStruct));
    //
    // do some useful stuff ...
    //
}

Now I’m assuming you have successfully built your DLL and everything is dandy there.

Next, actually putting this library into use. Enter C# :


using System;

using System.Interop.Services;

namespace Marshaling{

    //First : struct definitions
    //Simple structs have a 1-to-1 mapping:
    [StructLayout(LayoutKind.Sequential)]
	public struct SomeStruct
	{
		int a;
		int b;
	}

    //However, (unless you're using unsafe code - which is out of the scope of this post),
	//pointers are replaced by the managed type IntPtr:
    [StructLayout(LayoutKind.Sequential)]
    public struct MarshalStruct
    {
        int x;
        int y;
        IntPtr ptrToSomeStruct;
    }

    public class MarshalExample
    {
	    private MarshalStruct _ms;
		private SomeStruct _ss;

        //Function import - let's say the produced dll's name is "marshaling.dll"

        //'ref' keyword is used to pass a parameter by reference where otherwise - in C -
		//a pointer should be used.
        [DllImport("marshaling.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
        private static extern void func1(ref MarshalStruct marshal);

        public MarshalExample()
        {
		    _ms.x = 5;
			_ms.y = 10;
        }

		public void Func1Wrapper()
		{
		    func1(ref _ms);

			//Now, to see the data pointed to by ptrToSomeStruct we have to marshal back the contents:
			_ss = (SomeStruct)Marshal.PtrToStructure(_ms.ptrToSomeStruct, typeof(SomeStruct));
		}
    }

}

That’s it. Not that difficult, eh ?

An important note though about the “CallingConvention” part, you have to be positive that both the library function and its corresponding client code are using the same calling convention, otherwise the stack may be irreversibly destroyed and will result in very serious bugs.

Now, what if a function returns a pointer-to-struct ?
Simple and you already know it, Hint: IntPtr!
Example :
C snippet:

	__declspec(dllexport) struct __cdecl MarshalStruct* func2(void)
	{
		struct MarshalStruct* ms;
		//Some possibly useful stuff...
		return ms;
	}

C# snippet:

	private static extern IntPtr func2();

	public MarshalStruct Func2Wrapper()
	{
		IntPtr ptr = func2();
		MarshalStruct x = (MarshalStruct)Marshal.PtrToStructure(ptr, typeof(MarshalStruct));
		return x;
	}

Alright, last part of this post deals with arrays. In C, it’s perfectly natural in a struct definition to declare an array as a member, with a predefined fixed size. This is not the case with C# though since the array member can only have it’s size determined in an instance of the struct not in the struct definition itself. Fortunately, there’s a workaround.

Let’s say MarshalStruct was slightly altered :

struct MarshalStruct
{
	int x;
	int y;
	struct SomeStruct* ptrToSomeStruct;
	double	someArray[12];
};

The corresponding representation in C# would then be:

public struct MarshalStruct
{
	int x;
	int y;
	struct SomeStruct* ptrToSomeStruct;
	[MarshalAs(UnmanagedType.ByValArray, SizeConst=12)]
	double	someArray[12];
}

Now you can use this array as you would in C, and it works the same for any kind of arrays, even for arrays of structs.

That’s it for this post, hope it’s in anyway helpful. In part 2 I will be talking about function pointers/callbacks.

Articles

Dr. Michio Kaku – On The Future Of Our Civilization

In Future, Michio Kaku, Physics, Technology on November 16, 2010 by MT

This video is a must see, it’s a bit long, but it’s really worth the time (Dr. Kaku starts at 5:40 if you want to skip).

Articles

Pilot Post

In First Post on November 16, 2010 by MT

This is my first take at blogging. Still not sure what I’m going to write about nor even whether this blog is going to persist, or halt like many others – hopefully the former !

%d bloggers like this: