Get computer name via WSOCK32.DLL in C# - c#

I am migrating some VB6 code to C# (.NET 4.5.2) and got stuck into a piece of code that is calling the gethostname method from the WSOCK32.DLL to apparently retrieve the computer name. All the code samples that I have found so far point to
this code. And since I haven't been able to successfully PInvoke the gethostname method in C#, I can't help asking if is there an alternative to it.
This
[DllImport("WSOCK32.DLL", SetLastError = true)]
internal static extern long gethostname(string name, int nameLen);
string host = string.Empty;
var res = gethostname(host, 256);
fails with the following error:
The runtime has encountered a fatal error. The address of the error was at 0x6a13a84e, on thread 0xd88. The error code is 0xc0000005. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack.
I also read about using System.Environment.MachineName or the "COMPUTERNAME" environment variable, but I am interested in how the result differs than what gethostname method returns.
What options do I have?
I am developing on a 64bit system but I don't know if/how this affects working with WSOCK32.DLL since I found no documentation about it.

You cannot send an zero-length immutable C# string and expect it to get turned into something new. You are probably experiencing a buffer overflow. You need to use a StringBuilder instead:
[DllImport("WSOCK32.DLL", SetLastError = true)]
internal static extern long gethostname(StringBuilder name, int nameLen);
var builder = new StringBuilder(256);
var res = gethostname(builder, 256);
string host = builder.ToString();
More info here:
Passing StringBuilder to PInvoke function
C# PInvoke out strings declaration
http://pinvoke.net/default.aspx/ws2_32/gethostname.html
Also, there is really no reason for using that really old DLL function to get the name of the local computer. Just use System.Environment.MachineName instead.

Related

Converting some VB.NET code to C# - Need Advice

I am working with the original MMO that ever opened called VZones and they have a dll file that allows you to call the functions from this dll to do certain things within the program.
I have found some VB.NET code and the problem I am having is converting it to a way that will work with C# (using VS 2017)
You setup the DLL calls with this, which works fine:
[DllImport("vzdapi.dll", CharSet = CharSet.Ansi, SetLastError = true)]
public static extern string DapiGetText(string BufferIn, int LengthIn, int Timeout);
The problem is I need to convert this VB.NET code that is from someone else to what will work in C#. I have tried a few different options but the program just closes and never gives me an error.
object obj1 = (object)new string(char.MinValue, 32678);
vzText.Text = this.DapiGetText(Conversions.ToString(obj1), Strings.Len(RuntimeHelpers.GetObjectValue(obj1)), 1500);
The problem arises in the Conversions.ToString part, which I have of course tried to just make obj1.ToString() and that may work fine but the place I think is getting caught up is when it tries to run the middle code "Strings.Len(RuntimeHelpers.GetObjectValue(obj1))".
Does anyone have any help into getting this into something that will work in C#? Thanks!
I'm wondering if the conversions are necessary as the initial object you define is already a string, try the following solution:
string obj = new string(char.MinValue, Int16.MaxValue);
vzText.Text = this.DapiGetText(obj, obj.Length, 1500);

C# P/Invoke AccessViolationException when attepting to use string parameters

I'm trying to wrap a C++ dll for which I only have the header file for. The function I am trying to get working at the moment is giving me an AccessViolationException:
"Attempted to read or write protected memory.
This is often an indication that other memory is corrupt."
The C++ function prototype is:
RunSimulation( LPCSTR, LPSTR);
Meanwhile, my C# wrapper is:
[DllImport("thedll.dll", EntryPoint = "RunSimulation")]
public static extern uint RunSimulation(string simID, ref string outputID);
I suspect the problem is with the C# function, specifically with how the strings are implemented. Since I'm relatively new to platform invocation and such, I'm not sure how to proceed.
Should the string parameters be pointers to where the strings are? Or is there something else wrong with the wrapper maybe?
Edit:
This is how the function is called on the managed end of things:
string outputID = "";
try
{
RunSimulation(id, ref outputID);
}
catch (Exception e)
{
Logging.Log_Warning.SendException("Threw an exception", e);
}
Edit 2:
Upon changing the second parameter to a StringBuilder, the same exception occurs. The only difference is that the exception break doesn't stop at the line where the function is called, Visual Studio opens a new "Break" tab saying the exception happened. The function documentation recommends setting aside 16 bytes or more, so I used the capacity constructor with a values of 1024 and 4096 to test.
Edit 3:
After doing a clean and rebuild, the problem presented itself as a driver error. Since this shows that the API is functioning, the solution was indeed to change my ref string parameter to a StringBuilder as suggested in the comments.
The solution to my problem ended up being to use StringBuilder instead of String to make sure the space in memory was allocated ahead of time. So my signature ended up looking like:
[DllImport("thedll.dll", EntryPoint = "RunSimulation")]
public static extern uint RunSimulation(string simID, StringBuilder outputID);
And to use it:
string id = "someID";
int requiredSize = 512;
StringBuilder outputID = new StringBuilder(requiredSize);
RunSimulation(id, outputID);
Hope that helps!

Code Access Security is preventing PInvoking Setup API calls

I'm rewording this question since I understand a bit more now. Originally, what I had was too vague. I've discovered that I'm being routed by something called "Code Access Security." This is old-hat to everyone reading this, I'm sure, but not to me.
The application is very large so in a nutshell I have two assemblies. One is a utilities assembly with various "tools" used throughout the program. The other is calling upon these tools in order to function.
In the utilities assembly, there are many functions that are PInvoked but the one giving me grief is: SetupDiGetDeviceInterfaceDetail() (see here). My function prototype looks like this:
[DllImport("SetupApi.dll", SetLastError = true, CharSet = CharSet.Auto)]
[return : MarshalAs(UnmanagedType.Bool)]
public static extern bool SetupDiGetDeviceInterfaceDetail(
SafeHandleZeroOrMinusOneIsInvalid deviceInfoSet,
ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData,
IntPtr deviceInterfaceDetailData,
uint deviceInterfaceDetailDataSize,
IntPtr requiredSize,
IntPtr deviceInfoData);
In the assembly which uses this function, I'm using the two step process outlined in the remarks in order to gain the understanding of how much space I need to store the DevicePath which is in the SP_DEVICE_INTERFACE_DETAIL_DATA structure (see here). For example:
string GetDevicePath(SafeHandleSeroOrMinusOneIsInvalid hList, SP_DEVICE_INTERFACE_DATA infoSet)
{
IntPtr pReqSize = Marshal.AllocHGlobal(4);
Marshal.WriteInt32(pReqSize, 0);
uint reqSize;
// get the size needed
PInvoke.SetupDiGetDeviceInterfaceDetail(hList,
ref infoSet,
IntPtr.Zero,
0,
pReqSize,
IntPtr.Zero);
reqSize = (uint)Marshal.ReadInt32(pReqSize, 0);
IntPtr pDevInfoDetail = Marshal.AllocHGlobal((int)reqSize + 4); // +4 for cbSize
// call again, this time getting the actual data wanted
PInvoke.SetupDiGetDeviceInterfaceDetail(hList,
ref infoSet,
pDevInfoDetail,
reqSize,
IntPtr.Zero,
IntPtr.Zero);
string path;
// work .NET magic to read from unmanaged memory the path string and assign it
// to the above variable. Deallocate both unmanaged memory blocks.
return path;
}
The most frustrating thing is, these assemblies are used by two different programs. One is a GUI using the Visual Studio Isolated Shell. The other is simply a command line program. When the GUI is running, the above code is called and executes as expected. In the command line tool however, they fail (as described in the MSDN reference for this Setup API function) with some data about what happened. At this point, I'm able only to recover a portion of the data that is returned.
This is what comes back from the runtime:
stem.Security.PartialTrustVisibilityLevel, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
I know this has something to do with Code Access Security but I'm not at all sure how to fix. Using some suggestions that I've found thus far I've tried this attribute to the assembly (I placed it before the namespace block of code):
[assembly: AllowPartiallyTrustedCallers]
But this caused other compilation problems.
Please, anything would be most helpful and greatly appreciated.
Andy
Unfortunately, the problem isn't yet fixed. However, the problem appears to have nothing to do with Code Access Security as I first thought. I was being thrown a red herring. I stepped my way through the code using the memory window in Visual Studio and noticed that these strings were in memory before calling the Setup API function to fill them. Occasionally, I would get a different block of memory with different contents too, I just usually ended up with the contents I pasted.
The problem actually appears to have something to do with the 64 vs. 32 bit environments (at least, that's my theory at this point).
However, this question isn't the actual problem so I'm "answering" it to close it.

pinvoke to clutter function

I'm trying to pinvoke to a clutter function.
The function is defined in the docs as
ClutterActor * clutter_texture_new_from_file (const gchar *filename, GError **error);
The code I have is as follows:
[DllImport ("libclutter-glx-1.0.so.0")]
private static extern IntPtr clutter_texture_new_from_file (string filename, IntPtr errorData);
And I call it like this:
IntPtr texture = clutter_texture_new_from_file("myImage.jpeg",IntPtr.Zero);
however when called like this in monodevelop on ubuntu I get the following error.
Unix Transport Error
Eventally I would like to get the error reporting working so I can get the gerror result however firstly I need to get past the Unix Transport Error.
The errorData parameter should be marked as "ref IntPtr", although I don't think that should be causing this error since that parameter should be allowed to be NULL. Otherwise, try running this outside Monodevelop. This kind of error may be the result of a segfault elsewhere in your program.

Protected Memory Violation calling FORTRAN DLL from C#

I am trying to call out to a legacy dll compiled from FORTRAN code. I am new to Interop, but I've read some articles on it and it seems like my case should be fairly straightforward.
The method I really want to call has a complex method signature, but I can't even call this simple GetVersion method without getting a protected memory violation.
Here's my DllImport code:
[DllImport("GeoConvert.dll",
EntryPoint="_get_version#4",
CallingConvention=CallingConvention.StdCall)]
public static extern void GetGeoConvertVersion([MarshalAs(UnmanagedType.LPStr, SizeConst=8)]
ref string version);
Here's the FORTRAN code:
SUBROUTINE GetVer( VRSION )
C
!MS$DEFINE MSDLL
!MS$IF DEFINED (MSDLL)
ENTRY Get_Version (VRSION)
!MS$ATTRIBUTES DLLEXPORT,STDCALL :: Get_Version
!MS$ATTRIBUTES REFERENCE :: VRSION
!MS$ENDIF
!MS$UNDEFINE MSDLL
C
CHARACTER*8 VRSION
C
VRSION = '1.0a_FhC'
C
RETURN
END
Here's my unit test that fails:
[Test]
public void TestGetVersion()
{
string version = "";
LatLonUtils.GetGeoConvertVersion(ref version);
StringAssert.IsNonEmpty(version);
}
Here's the error message I get:
System.AccessViolationException
Message: Attempted to read or write protected memory.
This is often an indication that other memory is corrupt.
Other things I've tried:
Using the default marshalling
Passing a char[] instead of a string (get method signature errors instead)
...snip...
OK, I got it to work, the problem was passing by ref. I'm not sure why, but this works:
...snip...
You need to pass by reference because that is the semantic being used by the FORTRAN code. The client code is passing in a buffer that the FORTRAN code is going to write to in lieu of using a return value.
...snip...
!MS$ATTRIBUTES REFERENCE :: VRSION
...snip...
This attribute in your FORTRAN code specifies that this parameter is passed by reference. That means the FORTRAN code is going to write to this address. If the DllImport doesn't declare it as a ref value also, you will get an access violation.
OK, I got it to work, the problem was passing by ref. I'm not sure why, but this works:
[DllImport("GeoConvert.dll",
EntryPoint="_get_version#4",
CallingConvention=CallingConvention.StdCall)]
public static extern void GetGeoConvertVersion([MarshalAs(UnmanagedType.LPArray)]
byte[] version);
With this test:
[Test]
public void TestGetVersion()
{
//string version = "";
byte[] version = new byte[8];
LatLonUtils.GetGeoConvertVersion(version);
char[] versionChars = System.Text.Encoding.ASCII.GetChars(version);
string versionString = new string(versionChars);
}
Have you tried using a StringBuilder?
Create your String as a StringBuilder and pass that into the dll function.
Im unsure as to what Marashlling statement to use, perhapse the default might work.
Have a look at: Marshal C++ “string” class in C# P/Invoke
Heres a good article the might help as well: Interop Marshalling
I cannot try this solution since I do not have a FORTRAN compiler, but I think this would work for you:
[DllImport("GeoConvert.dll",
EntryPoint="_get_version#4",
CallingConvention=CallingConvention.StdCall,
CharSet=CharSet.Ansi)]
public static extern void GetGeoConvertVersion(StringBuilder version);
Thank you all guys, I've been trying to pass a string from c# to a subroutine from fortran dll and this method was the only working one among lots of others

Categories