Brief Example of Calling .dll Functions in C#

I don’t like C#, but the free version of Visual Studio only lets you use the interface builder in C#/.net programs, so here we are. My goal was to cheat and write the interesting parts of the program in C/C++, compiling to a .dll, and calling it from C#.

This has turned out to be an ordeal.

I have a great handle on calling functions in a .dll from Python. The CTypes module is amazing, and incredibly well documented. C# has a module (service?) in the System.Runtime.InteropServices namespace and the Platform Invoke service for “consuming un-managed code”, but it has been a real pain getting it to work.

I’ll admit that 80% of the problem is that I’m still fairly new to C#, but there is no shortage of information online for vanilla C# programming. Interfacing to a .dll seems to be uncommon enough that it’s hard to find exactly what I’m looking for when I run into a use-case that hasn’t been discussed much.

Here’s what I’m getting at. Let’s say I have a function in my .dll as such:

	return 42;

Here’s what the function in C# would look like for interfacing with GetInteger() in the .dll (which I put in a class called InteropStructTestDLLWrapper):

public extern static int GetInteger();

And here’s how to call that in C#:

int int_from_dll = 0;
int_from_dll = InteropStructTestDLLWrapper.GetInteger();

This behaves exactly as you would expect – it returns the number 42. Things start getting weird when pointers are involved.

Function in .dll:

INTEROPSTRUCTTEST_API void PassIntegerPointer(int *i)
	*i = 27;

Function for calling the .dll function in C#:

[DllImport(InteropStructTest.dll, CallingConvention = CallingConvention.Cdecl)]
public extern static void PassIntegerPointer([In, Out]ref int i);

Calling the function in C#:

InteropStructTestDLLWrapper.PassIntegerPointer(ref int_from_dll);

Now you have to deal with [In, Out] and ref, and CallingConvention.Cdecl. Much of this was guess-and-check to get working using information I gleaned from dozens of StackOverflow posts and other blogs. Things start getting extra weird when you want to pass a pointer to a struct or array of structs.

I decided it was best to just start making a sample .dll and .cs program that demonstrated a clear use-case for passing various data types to and from a .dll. Something that I could reference and add to as I learn. So far it has returning integers, passing a pointer to integer to be modified, passing a pointer to a struct to be modified, and passing an array of structs to be modified (which was super hard to find anything online about).

Right now it has examples of all the things I’ll have to do in small side-project I’m working on. I’ll flesh it out as needed.

Hopefully I’ll save someone some time. I’m embarrassed at how much time I burned getting this far!

Posted in Hobbies, Programming, Technology | Tagged , | Leave a comment

C# Struct Sizes

I’ve been banging my head against trying to get C# to talk to a .dll written in straight C for the past few days. I finally got a grip on passing basic data types, and pointers to basic data types, to/from my .dll, but I started getting garbage when passing pointers to structs and arrays of structs.

I wrote a master sanity check C# program and C .dll to demonstrate the correct methods for getting structs, pointers to structs, and arrays of structs into the .dll functions, and as soon as I clean it up and comment it I’ll post it.

One of my favorite sanity check tools in C is the sizeof() function, which tells you the size in bytes of a data type or struct. Well, C# has a sizeof() function, too, but it requires some verbosity to get the size of a struct out of it. It must have something to do with C# structs being memory managed. There are a few StackOverflow posts and other blog posts about how to do this, but they’re all overly complex or beyond the scope of simply getting the struct size, so here’s my take on it.

Here’s a small program that demonstrates how to get the size of C# structures.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;

namespace CSStructSize
    class Program
        public struct SimpleStruct
            public int firstInt;
            public int secondInt;

        public struct ComplexStruct
            public char firstChar;
            public char secondChar;
            public long firstLong;
            public short firstShort;
            public char thirdChar;
            public char fourthChar;
        static void Main(string[] args)
            Console.WriteLine("\nSize of C# char is: {0}", sizeof(char));
            Console.WriteLine("Size of C# short is: {0}", sizeof(short));
            Console.WriteLine("Size of C# int is: {0}", sizeof(int));
            Console.WriteLine("Size of C# long is: {0}", sizeof(long));
            Console.WriteLine("Size of SimpleStruct: {0}", Marshal.SizeOf(typeof(SimpleStruct)));
            Console.WriteLine("Size of ComplexStruct: {0}", Marshal.SizeOf(typeof(ComplexStruct)));

The output is:

Size of C# char is: 2
Size of C# short is: 2
Size of C# int is: 4
Size of C# long is: 8
Size of SimpleStruct: 8
Size of ComplexStruct: 24

Posted in Uncategorized | Leave a comment

File Open Dialog Box in Python

I’m putting the finishing touches on a side project at work that requires opening a file as an argument at the command line, or through a file open dialog box. Here’s a snippet that demonstrates how I implemented it.


import sys
import os

def choose_file():
        import Tkinter, tkFileDialog
    except ImportError:
        print "Tkinter not installed."
    #Suppress the Tkinter root window
    tkroot = Tkinter.Tk()
    return str(tkFileDialog.askopenfilename())
if __name__ == "__main__":
    #If no file is passed at the command line, or if the file
    #passed can not be found, open a file chooser window.
    if len(sys.argv) < 2:
        filename = os.path.abspath(choose_file())
        filename = os.path.abspath(sys.argv[1])
        if not os.path.isfile(filename):
            filename = choose_file()
    #Now you have a valid file in filename

It’s pretty straightforward. If no file is passed at the command line, or if the file passed at the command line isn’t a legitimate file, a file chooser dialog box pops up. If Tkinter isn’t installed, it bails out with an error message.

The bit about suppressing the Tk root window prevents a small box from appearing alongside the file chooser dialog box.


Posted in Programming | Leave a comment

Valve Trouble

It rained real hard Tuesday night. Wednesday morning at about 5am I’m stumbling in my kitchen trying to make coffee and I hear a hissing noise outside.

“Hah”, I says to myself, “my neighbors are watering their lawn on an off day. They’ll get fined by the city if caught”.

The wife goes out to walk the dog, and when she returns she asks me why I’m watering the back yard.

Ruh roh.

One of the sprinkler zones in my back yard was running, and could have been running since we went to bed at 9:30pm the night before. They weren’t running prior to that when I let the dog out before retiring to bed, so it must have spontaneously started itself at some point in the night, meaning it could have been running for up to seven and a half hours!

The control box in the garage didn’t indicate that it was active. I did the first obvious step: I turned it off and on again. No luck. Next I cycled the system through all the zones hoping it would kick it into normal operation. No luck.

I hadn’t even had my coffee yet, so I wasn’t firing on all cylinders. I grabbed a flashlight and started popping open all the valve holes in my yard hoping to at least find the one that was stuck, not knowing what in the world I’d do if I even found it. I could only find four (of the six), and they were all in my front yard. Fortunately I came across one larger covered hole in my front yard and noticed it said “Irrigation” on the cover. Inside there was a master faucet, and closing it finally shut the water off.

This post is a bit of self-flagellation. I’ve been in this house for two years now, and there are LOTS of things (important things!) that I’m still totally unfamiliar with. I should have known about this master faucet. I knew the box was there, but I had assumed it was some electrical thing.

After a bit of Googling how sprinkler systems work, I came to the tentative conclusion that the solenoid that controls the valve for that sprinkler zone must have shorted out and got stuck on – probably due to the rain. Thinking on it more (because solenoids are very simple) this could mean that one of the lines going to the solenoid is always hot, and the control box activates that solenoid by closing the path to ground. Rainwater buildup could have provided a conductive path to ground. There’s probably a good reason that the control box provides the ground path, and not the hot path. Or I could be totally wrong how it works.

I called Collin County Sprinkler that Wednesday morning, and they had someone out this morning (Thursday). It took them 20 minutes to find the valve hole (using a fancy wire tracing tool) and fix it. They showed me a busted seal that let rainwater into the valve and up into the solenoid, and confirmed my “rainwater allowed path to ground” hypothesis (or they were just humoring me because I was asking a lot of annoying questions).

Zone Five Valve

Fortunately my back yard slopes towards the alley so the excessive water didn’t get into the garage, and it’s hot outside so it evaporated very quickly. I don’t feel dumb not knowing where that valve was because it was very well hidden under the grass. There is one last valve I need to track down (which I forgot to ask about before they left), but I think I can find it on my own.

This incident is a big wake-up call for me. There are too many critical things in this house that I take on faith that they’re functional, and will stay functional – AC, plumbing, electricity, sprinklers, garage door, appliances, etc. I need to get a handle on those things. I don’t need to know every detail, but if something goes horribly wrong I need a plan.

Posted in Uncategorized | Leave a comment

Summer Plans

My involvement with Mojo Frankenstein is taking up all my hobby energy lately. We’ve been at it for about a year now and have gigs booked on over half the weekends through the summer (and growing).

I’ve been doing just enough programming for some office skunkworks projects that I don’t feel the need to do it at home to stay sane and keep the skills up. That’s good, I think.

That being said, here are some projects I’d like to tackle this summer.

  • Raspberry Pi security camera: I’m borrowing an RPi and I’d like to get some kind of minimal framework for a wireless network security camera happening. If OpenCV works on an RPi then I’m 80% there – the rest is figuring out where to dump images periodically (FTP?). There’s a great example of what I’m trying to accomplish here.
  • Re-write the Arduino Serial Communications tutorials: They still get ~40-60 page views daily, and I’ve learned so much in the past few years that I could easily make them better. I started writing a small e-book on the subject (using LeanPub) but couldn’t make enough material to justify going through the hassle. I would have had to include 5-10 example projects to demonstrate the material and I’m just not that creative.
  • Write about my ray-caster experiment: I’m bad at math, so I tackled a math-heavy(ish) project. I got results (rays were cast, walls were detected) but I was only able to figure out the naive way of doing it. There is a fancy way to do the ray casting using something called DDA, and I want to wait until I figure it out before writing it up. Every time I think I’ve worked it out with pencil and paper, I run into a massive wall (pun intended). It might be better to instead write about the process of learning this algorithm while I’m trying to learn it. That’s worked wonders for me before.
  • Write about problems I’ve having with Python package/module organization: I’ve been writing a semi-complicated Python package for work stuff. In an effort to be good I’ve tried to not just make it one monolithic .py file and split up the major classes into their own Python modules. For the life of me I can’t figure out any rhyme or reason to how the packages refer to each other, and what role has in it. Again, I want to be good and not just have “from foo import *” in every module since it’s considered bad form. I don’t want to put work stuff on this page, so I’d have to write a contrived example that demonstrates my point (and hope that someone on StackOverflow or /r/python can help me out). I’ve found legit issues with the documentation before, and I’m hoping that this is simply a matter of documentation being incomplete as opposed to me being dense.

I think that’s a pretty ambitious set of goals.

Posted in Hobbies, Programming, Technology | Leave a comment

Removing zeros from a Python tuple

I’ve been working with Python’s ctypes module to shuttle data back and forth with a Windows .dll. One of the arrays the .dll fills is pre-allocated, but not necessarily all used. So I’ll wind up with a tuple like this:


(42, 33, 89, 0, 0, 0, 0, 0, 0)

It’s harmless to have the trailing 0’s, but for the sake of tidiness I want to remove them. Python tuples are immutable, so there aren’t any methods for just chopping them out. What you can do is fill a new tuple with just the non-0 values. Here’s a fancy way of doing this using list comprehensions.

>>>some_data_fixed = tuple([x for x in some_data if x])


(42, 33, 89)

Which basically says to fill a list with x for every element x in some_data if it evaluates as true (meaning non-0), and then cast it to a tuple.

This example is in the official documentation for list comprehensions.

Posted in Programming | Leave a comment

Win32 and SFML noodling

I ran into a problem that I thought would be best solved by combining a prior UI framework and SFML. There are a zillion reasons you’d want to do this – if you need any kind of UI element (button, menu, text entry, etc) with an SFML project you quickly run into this crossroad.

GTK+, the only UI framework I’m familiar with, has a C API with its own wacky OOP implementation. There is a C++ binding called GTKMM, but some of the tutorials and code samples I’ve seen are bit off-putting.

I researched Qt and didn’t find a lot of hope there. Any framework that seems to insist on using its own development environment sounds like a bad time. There are Visual Studio plugins, but I didn’t see any clear indication that they would work with Visual Studio Express 2013.

Visual Studio Express 2013 obviously has Win32 support and project wizards built in, so what about that?


This seems to work. I referenced the Win32 sample on the SFML creator’s Github repository, as well as this outdated tutorial on the SFML site itself.

A few years back I ran through a few Win32 tutorials in order to understand some demo code at work, but the stuff that gets generated with VSE2013 looks nothing like it. I’m going to have to do a lot of research if I want to keep going forward with this.

There are lots of big questions, like how do I intercept SFML events? Does the Win32-generated window get them first, and I have to intercept/interpret those and then pass them to SFML? What about timing loops (a big deal in some of the game programming I’ve been doing)? Why does the window go white when I resize it?

Posted in Programming | Leave a comment