Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / Languages / Managed C++ / June 2005

Tip: Looking for answers? Try searching our database.

Managed C++ & P/Invoke in a web serice

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
MarkOwen - 16 Jun 2005 20:19 GMT
I am exploring using P/Invoke to call some legacy code from our customer
contact software. I have been trying some simple test scenarios and haven't
had success. Can someone point me to an example that shows how this can be
done? Here is a snippet of code I am trying:

Header file of C++ class for web service:

[DllImport("kernel32.dll", SetLastError=true)]
extern "C" bool GetComputerName(String *name, int *len);

Class file for web service:

String __gc* callKAPIClass::HelloWorld()
{
    String *p = "1234567890123456789012345678901234567890";
    int len = 30;
    bool rc = true;

    rc = GetComputerName(p, &len);
    int rc2 = Marshal::GetLastWin32Error();

    return p;
}

Unfortunately, I always get an error in GetComputerName().

Mark
Carl Daniel [VC++ MVP] - 16 Jun 2005 20:31 GMT
> I am exploring using P/Invoke to call some legacy code from our
> customer contact software. I have been trying some simple test
[quoted text clipped - 22 lines]
>
> Unfortunately, I always get an error in GetComputerName().

Not surprising, since GetComputerName doesn't have any idea what to do with
a String*.

My suggestion would be to not use PInvoke.  Rather, just call the function
from your C++ code and rely on IJW to bridge the managed/unmanaged gap.

<untested code>
#include <windows.h>

String __gc* callKAPIClass::HelloWorld()
{
char sz[MAX_COMPUTERNAME_LENGTH + 1];
int len = sizeof(sz);
bool rc = true;

rc = GetComputerName(sz, &len);
int rc2 = Marshal::GetLastWin32Error();

return Marshal.PtrToStringAuto(static_cast<IntPtr>(sz),len);
}
</untested code>

-cd

Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.