Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using a imported C dll

Status
Not open for further replies.

JontyMC

Programmer
Nov 26, 2001
1,276
GB
I have a C dll that I'm trying to import. I want to use a single function from the dll. The C definition is:

Code:
long NEAR_FindNearest(  char *FileName, 
 char *Postcode, 
 long MaxRecords, 
 double Radius, 
 NEAREST_INFO *NearestInfo); 

typedef struct  
{  
 int Count; 
 NEAREST_ITEM *NearestList; 
} NEAREST_INFO; 

typedef struct  
{  
 struct  
{  
 int Eastings; 
 int Northings; 
} Grid;  
 
 char *Record; 
 struct  
{  
 double Kilometres; 
 double Miles; 
} Distance;  
 
} NEAREST_ITEM;
At the moment I've got this code:
Code:
using System;
using System.Runtime.InteropServices;

namespace NearCode
{
	public class NearCode
	{
		[StructLayout(LayoutKind.Sequential)]
		public struct Grid
		{
			public int Eastings;
			public int Northings;
		}

		[StructLayout(LayoutKind.Sequential)]
		public struct Distance
		{  
			public double Kilometres;
			public double Miles;
		}

		[StructLayout(LayoutKind.Sequential)]
		public struct NearestItem 
		{
			public Grid Grid;
			public string Record;
			public Distance Distance;
		}

		[StructLayout(LayoutKind.Sequential)]
		public struct NearestInfo 
		{
			public int count;
			public NearestItem NearestItem;
		}

		[DllImport("NearAPI.dll")]
		static extern int NEAR_FindNearest(string FileName, string PostCode, int MaxRecords, double Radius, NearestInfo NearestInfo);

		public int FindNearest(string FileName, string PostCode, int MaxRecords, double Radius, NearestInfo NearestInfo)
		{
			return NEAR_FindNearest(FileName, PostCode, MaxRecords, Radius, NearestInfo);
		}
	}
}
And calling the function with:
Code:
NearCode.NearCode nc = new NearCode.NearCode();
NearCode.NearCode.NearestInfo ni = new NearCode.NearCode.NearestInfo();
Console.Write(nc.FindNearest("nearest.txt", "OX183PW", 12, 12, ni).ToString());
But this doesn't work. Any idea's what I'm doing wrong?


Jon

"I don't regret this, but I both rue and lament it.
 
I suspect I'm not using the pointers correctly, I've never done this before. Do I need to use the unsafe keyword?

Jon

"I don't regret this, but I both rue and lament it.
 
What is the calling convention in the original C DLL? cdecl, stdcall, etc.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top