This may be a daft question as I can see the security reason for it to happen the way it does...
I have a licensing c# project, this has a class which has a method which generates my license keys. I have made this method private as I do not want anybody else to be able to call my method for obvious reasons
The next thing I want to do is to have my user interface, which is in another c# project which is referencing the licensing dll to be the only other 'thing' which can access this method outside of itself, is this possible or do i need to move it into the same project so that it all compiles to the same dll and I can access its members?
LicensingProject
-LicensingClass
--Private MethodX (GeneratesLicenseKeys)
LicensingProject.UI
-LicensingUiClass
--I want to be able to be the only class to be able to access MethodX
There is a reason why the license Key Generator is not just in the UI, that is because the licensing works by generating a hash on itself and compares it to the one generated by the License Generator.
I would prefer not to all compile to the dll as my end users do not need the UI code.
I know that by common sense a private method, is just that. I am stumped.
You could make it an internal method, and use InternalsVisibleToAttribute to give LicensingProject.UI extra access to LicensingProject.
Merhdad's point about enforcement is right and wrong at the same time. If you don't have ReflectionPermission, the CLR will stop you from calling things you shouldn't - but if you're using reflection from a fully trusted assembly, you can call anything. You should assume that a potential hacker is able to run a fully trusted assembly on his own machine :)
None of this will stop someone from using Reflector to decompile your code. In other words, making it private isn't really adding a significant amount of security to your licensing scheme. If anyone actually puts any effort into breaking it, they'll probably be able to.
This is really a comment, in response to Mehrdad's point about the runtime not performing access checks; here, you can see the JIT (it transpires) performing the access check - not reflection, and not the C# compiler.
To fix the code, make Foo.Bar public. Interestingly, it also verifies that Foo is accessible - so make Foo internal to see more fireworks:
using System;
using System.Reflection;
using System.Reflection.Emit;
static class Program {
static void Main() {
MethodInfo bar = typeof(Foo).GetMethod("Bar",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
var method = new DynamicMethod("FooBar", null, new[] {typeof(Foo)});
var il = method.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.EmitCall(OpCodes.Callvirt, bar, null);
il.Emit(OpCodes.Ret);
Action<Foo> action = (Action<Foo>) method.CreateDelegate(typeof(Action<Foo>));
Foo foo = new Foo();
Console.WriteLine("Created method etc");
action(foo); // MethodAccessException
}
}
public class Foo {
private void Bar() {
Console.WriteLine("hi");
}
}
public, private, ... stuff are just enforced by the compiler. You can use reflection to access them pretty easily (assuming the code has required permissions, which is a reasonable assumption as he has complete control on the machine). Don't rely on that assuming nobody can call it.
Foo.Bar may stay private...
To fix the code above, add one parameter at end of DynamicMethod constructor:
var method = new DynamicMethod("FooBar", null, new[] {typeof(Foo)}, true);
Add true to skip JIT visibility checks on types and members accessed by the MSIL of the dynamic method.
Related
Assume I have 2 dlls maintained by 2 different teams:
Team1.dll (v1.0)
public class Foo
{
int GetValue() { return 3; }
}
Team2.dll (v1.0)
public class Bar
{
public int IncFooValue(Foo foo) { return foo.GetValue() + 1; }
}
When Team1.dll (v1.0) and Team2.dll (v1.0) are executed, everything is fine. But assume that Team1.dll were changed & the method Foo.GetValue() were removed (v1.1) and dropped next to Team2.dll (all without rebuilding Team2.dll). If executed, then you would get a MissingMethodException.
Question: How could I detect if Team1.dll is no longer compatible with Team2.dll without executing them?
For example, something like:
Foreach Class in Team2.dll
Foreach Method in Class
Foreach Instruction in Method
If Instruction not exists in Team1.dll
Throw "Does not exist"
It is possible to detect missing methods by forcing JIT compilation of your methods.
For that you just need enumerate all methods in your assemblies using reflection and then call RuntimeHelpers.PrepareMethod(method.MethodHandle) for each of them.
The tricky part here is dealing with generics. If your method or class contains generics, you also need to specify the concrete types for which your generic method will be jitted:
Type[] classGenericArgs = ...;
Type[] methodGenericArgs = ...;
Type[] allGenericArgs = classGenericArgs.Concat(methodGenericArgs).ToArray();
RuntimeHelpers.PrepareMethod(method.MethodHandle, allGenericArgs.Select(p => p.TypeHandle).ToArray());`
If your generic arguments also have constraints, you need to make sure that the types you choose satisfy these constraints, otherwise, jitting will fail.
Satisfying constraints can be difficult, so I wrote a Jitter class to automate this. It forces load of all libraries referenced by your application into memory and runs jitting with automatically substituting appropriate concrete classes for your generic methods (if possible). The usage for it is simple, just specify which assemblies you want jitted:
Jitter.RunJitting(asm => asm.FullName.StartsWith("My.Company.Namespace"));
Make sure your .NET app references all assemblies you want to verify.
You can find the source code for Jitter here. It is far from perfect, but is able to jit 99.8% of all methods in our codebase and detect broken package dependencies for us.
Check if the type contains the definition of the method.
if (foo.GetType().GetMethod("GetValue") != null)
{
return foo.GetValue() + 1;
}
as others have suggested you may be better off pursuing another strategy (better versioning/backwards compatibility or handling the exception on the calling end.
Consider the code below. Looks like perfectly valid C# code right?
//Project B
using System;
public delegate void ActionSurrogate(Action addEvent);
//public delegate void ActionSurrogate2();
// Using ActionSurrogate2 instead of System.Action results in the same error
// Using a dummy parameter (Action<double, int>) results in the same error
// Project A
public static class Class1 {
public static void ThisWontCompile() {
ActionSurrogate b = (a) =>
{
a(); // Error given here
};
}
}
I get a compiler error 'Delegate 'Action' does not take 0 arguments.' at the indicated position using the (Microsoft) C# 4.0 compiler. Note that you have to declare ActionSurrogate in a different project for this error to manifest.
It gets more interesting:
// Project A, File 1
public static class Class1 {
public static void ThisWontCompile() {
ActionSurrogate b = (a) => { a(); /* Error given here */ };
ActionSurrogate c = (a) => { a(); /* Error given here too */ };
Action d = () => { };
ActionSurrogate c = (a) => { a(); /* No error is given here */ };
}
}
Did I stumble upon a C# compiler bug here?
Note that this is a pretty annoying bug for someone who likes using lambdas a lot and is trying to create a data structures library for future use... (me)
EDIT: removed erronous case.
I copied and stripped my original project down to the minimum to make this happen. This is literally all the code in my new project.
FINAL UPDATE:
The bug has been fixed in C# 5. Apologies again for the inconvenience, and thanks for the report.
Original analysis:
I can reproduce the problem with the command-line compiler. It certainly looks like a bug. It's probably my fault; sorry about that. (I wrote all of the lambda-to-delegate conversion checking code.)
I'm in a coffee shop right now and I don't have access to the compiler sources from here. I'll try to find some time to reproduce this in the debug build tomorrow and see if I can work out what's going on. If I don't find the time, I'll be out of the office until after Christmas.
Your observation that introducing a variable of type Action causes the problem to disappear is extremely interesting. The compiler maintains many caches for both performance reasons and for analysis required by the language specification. Lambdas and local variables in particular have lots of complex caching logic. I'd be willing to bet as much as a dollar that some cache is being initialized or filled in wrong here, and that the use of the local variable fills in the right value in the cache.
Thanks for the report!
UPDATE: I am now on the bus and it just came to me; I think I know exactly what is wrong. The compiler is lazy, particularly when dealing with types that came from metadata. The reason is that there could be hundreds of thousands of types in the referenced assemblies and there is no need to load information about all of them. You're going to use far less than 1% of them probably, so let's not waste a lot of time and memory loading stuff you're never going to use. In fact the laziness goes deeper than that; a type passes through several "stages" before it can be used. First its name is known, then its base type, then whether its base type hierarchy is well-founded (acyclic, etc), then its type parameter constraints, then its members, then whether the members are well-founded (that overrides override something of the same signature, and so on.) I'll bet that the conversion logic is failing to call the method that says "make sure the types of all the delegate parameters have their members known", before it checks the signature of the delegate invoke for compatibility. But the code that makes a local variable probably does do that. I think that during the conversion checking, the Action type might not even have an invoke method as far as the compiler is concerned.
We'll find out shortly.
UPDATE: My psychic powers are strong this morning. When overload resolution attempts to determine if there is an "Invoke" method of the delegate type that takes zero arguments, it finds zero Invoke methods to choose from. We should be ensuring that the delegate type metadata is fully loaded before we do overload resolution. How strange that this has gone unnoticed this long; it repros in C# 3.0. Of course it does not repro in C# 2.0 simply because there were no lambdas; anonymous methods in C# 2.0 require you to state the type explicitly, which creates a local, which we know loads the metadata. But I would imagine that the root cause of the bug - that overload resolution does not force loading metadata for the invoke - goes back to C# 1.0.
Anyway, fascinating bug, thanks for the report. Obviously you've got a workaround. I'll have QA track it from here and we'll try to get it fixed for C# 5. (We have missed the window for Service Pack 1, which is already in beta.)
This probably is a problem with type inference, apperently the compiler infers a as an Action<T> instead of Action (it might think a is ActionSurrogate, which would fit the Action<Action>> signature). Try specifying the type of a explicitly:
ActionSurrogate b = (Action a) =>
{
a();
};
If this is not the case - might check around your project for any self defined Action delegates taking one parameter.
public static void ThisWontCompile()
{
ActionSurrogate b = (Action a) =>
{
a();
};
}
This will compile. Some glitch with the compiler its unable to find the Action delegate without parameters. That's why you are getting the error.
public delegate void Action();
public delegate void Action<T>();
public delegate void Action<T1,T2>();
public delegate void Action<T1,T2,T3>();
public delegate void Action<T1,T2,T3,T4>();
It probably isn't even possible to do this, but I will ask anyway.
Is it possible to create a function that receives a string and then uses it as a right side argument for the goes to operator (=>) used in lambda?
Actually, what I want to do is to be able to redefine an specific method of a specific class during runtime. I want to be write down a function with the program running and attaching it to a delegate. Is it possible?
You have several ways how to do it:
dynamically create lambda expression (look at Dynamic LINQ: Part 1)
dynamically create CodeDom model and compile it at run-time (look at CodeDom.Compiler namespace
dynamically create C#/VB.NET source code and compile it at run-time (look at CSharpCodeProvider and VBCodeProvider classes )
dynamically create object model, which can do same things like the method (look at Strategy Design Pattern
The easiest way to do it is probably DLINQ as TcKs suggested.
The fastest (I believe, in 3.5) is to create a DynamicMethod. Its also the scariest method as well. You're essentially building a method using IL, which has about the same feel as writing code in machine language.
I needed to do this to dynamically attach event handlers in some thing or another (well, I didn't need to do it, I just wanted to make unit testing events easier). It seemed a bit daunting at the time because I don't know crap about IL, but I figured out a simple way to accomplish this.
What you do is create a method that does exactly what you want. The more compact the better. I'd provide an example if I could figure out exactly what you're trying to do. You write this method in a class within a DLL project and compile it in release mode. Then you open the DLL in Reflector and disassemble your method. Reflector gives you the option of what language you wish to disassemble to--select IL. You now have the exact calls you need to add to your dynamic method. Just follow the example on MSDN, switching out the example's IL for your reflected methods' code.
Dynamic methods, once constructed, invoke at about the same speed as compiled methods (saw a test where dynamic methods could be called in ~20ms where reflection took over 200ms).
Your question is pretty unclear, but you can certainly use expression trees to create delegates dynamically at execution time. (There are other ways of doing it such as CodeDOM, but expression trees are handier if they do all you need. There are significant restrictions to what you can do, however.)
It's often easier to use a lambda expression with some captured variables though.
For example, to create a function which will add the specified amount to any integer, you could write:
static Func<int, int> CreateAdder(int amountToAdd)
{
return x => x + amountToAdd;
}
...
var adder = CreateAdder(10);
Console.WriteLine(adder(5)); // Prints 15
If this doesn't help, please clarify your question.
Not that I am recommending this over the other better options, but there is a 7th method and thats to use AssemblyBuilder,ModuleBuilder,TypeBuilder, and MethodBuilder in the System.Reflection.Emit namespace to create a dynamic assembly. This is the same similar voodoo as using DynamicMethod.
For example you could use these to, at runtime, create a proxy class for a type and override virtual methods on that type.
To get you started here is some code...
using System;
using System.Reflection;
using System.Reflection.Emit;
var myAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(
new AssemblyName("Test"), AssemblyBuilderAccess.RunAndSave);
var myModule = myAssembly.DefineDynamicModule("Test.dll");
var myType = myModule.DefineType("ProxyType", TypeAttributes.Public | TypeAttributes.Class,
typeof(TypeToSeverelyModifyInAnUglyWayButItsNecessary));
var myMethod = myType.DefineMethod("MethodNameToOverride",
MethodAttributes.HideBySig | MethodAttributes.Public,
typeof(void),Type.EmptyTypes);
var myIlGenerator = myMethod.GetILGenerator();
myIlGenerator.Emit(OpCodes.Ret);
var type = myType.CreateType();
Use .net core 3.1, you can create dynamic method with IL language(mono is same as well):
using System.Linq.Expressions;
using System.Reflection.Emit;
class Program
{
static void Main()
{
DynamicMethod hellomethod = new DynamicMethod("WriteLine", typeof(void), new[] { typeof(string) }, typeof(Program).Module);
ILGenerator il = hellomethod.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }));
il.Emit(OpCodes.Ret);
Action<string> hello4 = (Action<string>)hellomethod.CreateDelegate(typeof(Action<string>));
hello4("Hello World!");
}
}
If you declare the method as virtual, you might be able to use Castle's DynamicProxy to substitute a dynamically-generated (with one of the other answer's methods) implementation at runtime:
Castle DynamicProxy is a library for generating lightweight .NET proxies on the fly at runtime. Proxy objects allow calls to members of an object to be intercepted without modifying the code of the class. Both classes and interfaces can be proxied, however only virtual members can be intercepted.
The second paragraph in your question suggests that really what you might be after is straightforward IOC (Inversion of Control)
Instead of declaring an instance of your class, you declare an instance of an interface and based on whatever condition you choose, you use the particular overriding class with the correct method in it. Hope that makes sense.
You should check to see if your problem can be solved with simple polymorphism first. Unless you're defining abstract interoperability to another language or editing the compiler, trying to change a method at runtime is probably the wrong solution to the problem.
I use Stylecop for Resharper and whenever I call something in my class, Stylecop tells me to use the this keyword. But the IDE says this is redundant code (which it sure is), so why should I use the this keyword?
Does redundant code mean its not needed (obviously) and the compiler won't even do anything with the this keyword? So I assume the this keyword is just for clarity.
Also, with the CLR, do things like this fall consistently across languages? So if the answer is that the compiler doesn't even touch the this keyword and it is just for presentation and clarity, then the same is true for VB.NET? I assume it is all for clarity as stylecop keeps an eye on this and Fxcop (which I will use later on) keeps an eye on my code's quality from a technical point of view.
Thanks
It's for clarity and to prevent any ambiguity between a class member and a local variable or parameter with the same name.
The IL it compiles to will not be any different.
Most of the time is just for clarity but some times it is required.
using System;
class Foo
{
String bar;
public Foo(String bar)
{
this.bar = bar;
}
}
Here you will need this as it serves to disambiguate between the field bar and the constructor parameter bar. Obviously changing the name of the parameter or field could accomplish the same thing.
In all cases, there is no performance difference with/without the this - the compiler still does it implicitly, injecting a ldarg.0 into the IL.
Just for completeness, there is one other mandatory use of this (excluding disambiguation, ctor-chaining, and passing this to other methods): extension methods. To call an extension method on the current instance, you must qualify with this (even though for a regular method it would be implicit).
Of course, in most cases, you would simply add a regular instance method to the class or a base-class...
class Foo {
void Test() {
this.Bar(); // fine
Bar(); // compiler error
}
}
static class FooExt {
public static void Bar(this Foo foo) { }
}
In C# this is a reference to the current instance of the class (it's me in VB.NET). It's used generally to fully qualify a class member. For example, consider this C# class:
public class MyClass
{
int rate;
private void testMethod()
{
int x;
x = this.rate;
}
}
this isn't required in the code above, but adds instant clarity when reading the code that rate belongs to the class rather than the method (search SO, you'll find lots of opinions about the use of this). It's semantic behavior is the same in VB--and its use doesn't impose a performance penalty.
Apart from the clarity examples provided the only other valid usage of the "this" keyword is to pass the current instance of an object as a paremeter.
It is just for clarity, and one can argue about what is better. Python doesn't support omitting the "self" identifier at all.
Also, with the CLR, do things like this fall consistently across languages? So if the answer is that the compiler doesn't even touch the this keyword and it is just for presentation and clarity, then the same is true for VB.NET?
In JVM for sure (and also for CLR, I'm almost sure) the code for the "this" keyword is always generated, even if that is omitted from the source - so it's like if the this keyword is always added. So, I don't think that any .NET compiler could generate different output, so there can't be a performance penalty.
Then, it depends on the language. For instance JScript (and even JScript.NET) does not allow to omit "this", like Python, because there are functions (so "this.a()" is a method invocation, "a()" is a function invocation), and because the compiler does not know the members of any types - they're only known at runtime (well, this is not an impossible problem to solve indeed, the other issue is more relevant).
In C#, is there a way to instantiate an instance of a class without invoking its constructor?
Assume the class is public and is defined in a 3rd party library and the constructor is internal. The reasons I want to do this are complicated but it would be helpful to know if it's possible using some kind of C# hackery.
NOTE: I specifically do not want to call any constructor so using reflection to access the internal constructor is not an option.
I have not tried this, but there is a method called FormatterServices.GetUninitializedObject that is used during deserialization.
Remarks from MSDN says:
Because the new instance of the object
is initialized to zero and no
constructors are run, the object might
not represent a state that is regarded
as valid by that object.
Actually it sounds like they made the constructor internal just so you can't instantiate it. It may have a builder or factory method.
Check out these articles:
Preventing Third Party Derivation: Part 1
Preventing Third Party Derivation: Part 2
they kind of explain the reasoning.
Contrary to what many believe, a constructor hasn't much to do with the instantiation of an object at all (pretty misleading term). A constructor is a special method that can be called after the instantiation of an object to allow that object to properly initialize itself. In C++ object instantiation allocates memory for the object, in .NET and Java it is both allocated and pre-initialized to default values depending on the type of fields (0, null, false etc.). Then the run-time calls the constructor. The new operator encapsulates these two separate actions into what appears to be a single operation.
Deserialization could never had worked in .NET if it wasn't possible to create an instance without using a constructor. That said, the so called ConstructorInfo type acts as both a new operator and constructor when calling its Invoke(...) method.
See RuntimeHelpers.GetUninitializedObject(Type), available in .NET Core 2.0 / .NET Standard 2.1 and above.
Another answer suggests
FormatterServices.GetUninitializedObject(Type), which directly proxies to RuntimeHelpers.
For completeness, if you want to create an uninitialized object of the same type as another instance, in .NET Core 7 there is also an undocumented AllocateUninitializedClone, with sample code below. I wouldn't recommend this over simply passing instance.GetType() to the documented API.
Likewise, here are notes for if you actually want to hit an internal constructor:
Given a Type and some arguments.
Use Activator.CreateInstance(Type type, object[] args).
Alternatively via Reflection APIs
Use type.GetConstructor. The returned ConstructorInfo has an Invoke method. If you pass an instance, you will effectively reinitialize an object. If you pass no instance, the invocation will instantiate a new object.
Some sample code:
using System.Reflection;
using System.Runtime.CompilerServices;
public static class Program {
public static void Main() {
//
// create uninitialized object instance, then run ctor on it
//
var inst1 = (C)RuntimeHelpers.GetUninitializedObject(typeof(C));
Console.WriteLine(inst1.X); // 0
var ctor = typeof(C).GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, Array.Empty<Type>());
ctor.Invoke(inst1, null); // Prints "Ran C's Ctor. X is -123"
Console.WriteLine(inst1.X); // 2
//
// create new object with ctor (via reflection)
//
var inst2 = (C)ctor.Invoke(null); // Prints "Ran C's Ctor. X is -123"
Console.WriteLine(inst2.X); // 2
//
// create new object with ctor (via activator)
//
var inst3 = (C)Activator.CreateInstance(typeof(C), BindingFlags.Instance | BindingFlags.NonPublic, null, null, null); // Prints "Ran C's Ctor. X is -123"
Console.WriteLine(inst3.X); // 2
//
// create new uninitialized object of type matching a given instance via undocumented AllocateUninitializedClone
//
var allocateUninitializedClone = typeof(RuntimeHelpers).GetMethod("AllocateUninitializedClone", BindingFlags.Static | BindingFlags.NonPublic, new[] { typeof(object) });
var inst4 = (C)allocateUninitializedClone.Invoke(null, new []{inst2});
Console.WriteLine(inst4.X); // 0
}
public class C {
private C() {
Console.WriteLine($"Ran C's Ctor. X is {X}");
X = 2;
}
public int X { get; } = -123;
}
}
It might be possible to access the constructor via reflection and invoke it like that (but I'm not sure that it will work since the constructor is internal - you'll have to test it).
Otherwise from my knowledge you can't create an object without calling the constructor.
EDIT: You updated your question, you want to construct a class without a constructor. Or call a default "Empty Constructor".
This cannot be done, as the compiler will not generate a default constructor if there is already one specified. However, for the benefit of the readers, here is how to get at a internal, protected, or private constructor:
Assuming your class is called Foo:
using System.Reflection;
// If the constructor takes arguments, otherwise pass these as null
Type[] pTypes = new Type[1];
pTypes[0] = typeof(object);
object[] argList = new object[1];
argList[0] = constructorArgs;
ConstructorInfo c = typeof(Foo).GetConstructor
(BindingFlags.NonPublic |
BindingFlags.Instance,
null,
pTypes,
null);
Foo foo =
(Foo) c.Invoke(BindingFlags.NonPublic,
null,
argList,
Application.CurrentCulture);
Ugly, but works.
Of course, there may be a perfectly legitimate reason to mark a constructor as internal, so you should really consider the logistics of what you want before you abuse that class by getting at it with reflection.
You have to call a constructor to create an object. If there are none available to your liking perhaps you could use a byte code rewriting library like the Mono project's Cecil. It works on Windows as well as Linux. From some of the demos I saw, it looked pretty cool. You can change the protection levels of methods and all sorts of crazy stuff.
If the class (and the classes of objects that it references) is Serializable, you can create a deep copy by serializing using a BinaryFormatter that outputs to a MemoryStream (creating a byte array byte[]), then deserializing. See the answers to this question on converting an object to a byte array. (But note - saving the byte array to use later/elsewhere is likely not to work. IOW don't save the byte array to a file or other persistent form.)
See the System.Activator.CreateInstance function.
What you are asking to do is a violation of the philosophy upon which managed programming was developed. The .Net Framework and C# are built with the principle that, whenever possible, objects should be abstracted away from their underlying memory. Objects are objects, not a structured array of bytes. This is why you can't cast objects to void pointers willy-nilly. When objects are abstracted away from their underlying memory, it is fundamentally invalid to suggest that an object instance can exist without the constructor being invoked.
That said,the .Net framework has made concessions to the fact that in reality, objects are actually represented in memory. With some creativity, it is possible to instantiate value types without invoking their initializers. However, if you feel you need to do it, you're probably doing things wrong.
I noticed the "deadness" of the subject but just for clarification on further readers and to put a final answer that maybe wasn't possible when the question was posted. Here it goes.
It seems that you can instantiate a class without using it's constructors by assigning values to its properties. Here is the address where is the how-to in MSDN for this type of instantiation http://msdn.microsoft.com/en-us/library/bb397680.aspx.
It seems like this is a technique that's not well known because I encountered it in a article in CodeProject and then googled it and didn't find anything about it and later on visited the MSDN Homepage and there was a post that linked me to that exact subject. So it seems that it's an unknown subject rather than a new one because the date on the CodeProject post dates May 2008.
Hope this helps someone else that google's this and comes across with this question.
No one here has quite clarified what is meant by "It can't be done."
The constructor is what creates the object. Your question is akin to "How can I build a sand castle without shaping it like a castle?" You can't -- All you will have is a pile of sand.
The closest thing you could possible do is to allocate a block of memory the same size as your object:
byte[] fakeObject = new byte[sizeof(myStruct)];
(NOTE: even that will only work in MyStruct is a value type)