473,785 Members | 2,851 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Help please with pointers to callbacks in structs

I am very new to C# programming and have run into a problem.

I apologize for the repost of this article. For some reason, my news
reader attached it to an existing thread.

First off, I have an SDK that I have written for C/C++ and would like to
port it to C# if at all possible.

Basically, I've got a structure that I need to pass to the C-style DLL
(i.e. no mangled names - everything is __stdcall). This structure needs
to contain pointers to callback functions that the DLL can use to notify
the C# application when certain events occur. In addition, I need to use
SetEnvironmentV ariable and pass a string containing a pointer to a
character array for special processing by the DLL. I've included some
code that shows basically everything I'm looking to do.

To save time, I understand how to get access to exported functions within
DLLs.
// this structure will be filled by the DLL and will be passed
// to the callback for function2, (i.e. FnPtr2's typedef)

typedef struct _toPassAsArgume ntStruct
{
int a;
int b;
double c;
} TO_PASS_AS_ARGU MENT;
// these are the typedef's for two callback functions that will be
// stored in the structure, DEMOSTRUCT

typedef BOOL (__stdcall *FnPtr1)(DWORD i, char *path, DWORD pathLength);
typedef BOOL (__stdcall *FnPtr2)(TO_PAS S_AS_ARGUMENT *structure);
typedef struct _demoStruct
{
FnPtr1 function1;
FnPtr2 function2;
} DEMOSTRUCT;
char global_text[5] = {"test"};
// MyFunction1 and MyFunction2 are called by the DLL

BOOL MyFunction1(DWO RD i, char *path, DWORD pathLength)
{
strcpy(path, "unknown");
return TRUE;
}

BOOL MyFunction2(TO_ PASS_AS_ARGUMEN T *structure)
{
structure->a = 5;
return TRUE;
}
// simple_function is called by the non-DLL (i.e. the application)

void simple_function ()
{
char text[128] = {0};

DEMOSTRUCT ds = {0};

// Are these four statements possible in C#?

ds.function1 = MyFunction1;
ds.function2 = MyFunction2;

// the contents of 'text' will be passed to the DLL.
sprintf(text, "%x", &global_text );

SetEnvironmentV ariable("test", text);
}
--

TIA,
Brian
Nov 16 '05
22 1390
> You could use sprintf (c/c++ runtime) but there is a difference in calling
convention, sprintf uses __cdecl. You can call it from c# but you can't
have variable arguments therefore all arguments must be declared eg :
Oh, yeah.... I forgot about that little gotcha.
[DllImport("msvc rt.dll", CharSet=CharSet .Ansi,
CallingConventi on=CallingConve ntion.Cdecl)]
public static extern int sprintf(IntPtr pDest, String format, int i, String
s); And I don't think you need it, you can use .Net formatting capabilities :
string s = Format( "{0} {1}", 10, "test" ); // eg
lstrcpyA( pData, s );
That's what I'll recommend should anyone ask about it. Obviously, sprintf
would be a pain to use.


Out of morbid curiosity, any particular reason why C# is so 'protective' It's not just c#, all net languages compile to ilasm where most of the
restrictions come from.
The idea is to produce more secure and stable applications. of its data? In the land of C (sort of a contradiction there,
phonetically speaking), it's possible to do just about anything to
anybody. Altough I like c it leads to hard to find bugs.
But entomology is fun! :)

C# seems to want keep a tight reign of its data. I'm assuming
its for security reasons, but it sure makes it rough on the 'die-hard' C
programmers.

You should just forget about pointers when you use c# and learn the class
library which has a lot of functionality.


I shall forget. Now what were we talking about??? :) Seriously though,
I've got a couple of books on C#, so hopefully those plus the very helpful
suggestions I've gotten from you will be enough to see me through.

Thanks again,
Brian
Nov 16 '05 #21
I had a problem with the lstrcpyA function. I watched the memory on the
destination string, and only the first character of the src string was
copied due to its unicode nature. I wrote the following function to take
care of the issue. Is there a better way. The destination string is a
non-unicode string.

public int CopyString(stri ng src, IntPtr dest, UInt32 len)
{
byte [] copiedSrc;
if (len < src.Length)
{
return 0;
}

copiedSrc = new byte [src.Length];

for (int i=0; i<src.Length; i++)
{
byte b = (byte)src[i];
copiedSrc[i] = b;
}

lstrcpyA(dest, copiedSrc);

return src.Length;
}
<big snip>

Thanks,
Brian
Nov 16 '05 #22
Hi,

<Brian> wrote in message news:10******** *****@corp.supe rnews.com...
I had a problem with the lstrcpyA function. I watched the memory on the
destination string, and only the first character of the src string was
copied due to its unicode nature.
[DllImport(@"ker nel32.dll", CharSet=CharSet .Ansi)]
public extern static void lstrcpyA(IntPtr p, string s);

Because of the CharSet.Ansi parameter the framework should first re-code the
unicode string (s) into an ansi one before copy. It works for me, don't
know why you see this behaviour.
I wrote the following function to take
care of the issue. Is there a better way. The destination string is a
non-unicode string.
There's a better way (managed) to convert an unicode string into ansi bytes
and then you don't need lstrcpyA anymore but you can use Marshal.Copy :

public int CopyString( string src, IntPtr dest, UInt32 len )
{
// truncate if src too long
if ( src.Length > (len-1) ) src = src.Substring(0 , len-1);

// Get ansi bytes including null terminator
byte [] temp = System.Text.Enc oding.Default.G etBytes( src + '\0' );

Marshal.Copy( temp, 0, dest, temp.Length );
return src.Length;
}

hth,
Greetings

public int CopyString(stri ng src, IntPtr dest, UInt32 len)
{
byte [] copiedSrc;
if (len < src.Length)
{
return 0;
}

copiedSrc = new byte [src.Length];

for (int i=0; i<src.Length; i++)
{
byte b = (byte)src[i];
copiedSrc[i] = b;
}

lstrcpyA(dest, copiedSrc);

return src.Length;
}
<big snip>

Thanks,
Brian

Nov 16 '05 #23

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

23
2246
by: Brian | last post by:
I am very new to C# programming and have run into a problem. I apologize for the repost of this article. For some reason, my news reader attached it to an existing thread. First off, I have an SDK that I have written for C/C++ and would like to port it to C# if at all possible. Basically, I've got a structure that I need to pass to the C-style DLL (i.e. no mangled names - everything is __stdcall). This structure needs
25
1429
by: Brian | last post by:
I am very new to C# programming and have run into a problem. I apologize for the repost of this article. For some reason, my news reader attached it to an existing thread. First off, I have an SDK that I have written for C/C++ and would like to port it to C# if at all possible. Basically, I've got a structure that I need to pass to the C-style DLL (i.e. no mangled names - everything is __stdcall). This structure needs
0
9645
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9480
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10329
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10092
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9950
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8974
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5381
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3650
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2880
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.